【设计模式】—— 策略模式Strategy

简介:

  模式意图

  定义一系列的算法,把他们封装起来,使得算法独立于适用对象。

  比如,一个系统有很多的排序算法,但是使用哪个排序算法是客户对象的自有。因此把每一个排序当做一个策略对象,客户调用哪个对象,就使用对应的策略方法。

  应用场景

  1 当许多的类,仅仅是行为或者策略不同时,可以把行为或策略单独提取出来,这样主体的类就可以进行统一了。

  2 需要使用不同的算法。

  3 一个类定义了多种行为。

  模式结构

  Context 环境角色的,策略的调用者

复制代码
class Context{
    private Strategy strategy;
    public Strategy getStrategy() {
        return strategy;
    }
    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
    public void operation(){
        strategy.action();
    }
}
复制代码

  Strategy 策略的抽象,规定了统一的调用接口

interface Strategy{
    public void action();
}

  ConcreteStrategy 具体的策略

复制代码
class ConcreteStrategy1 implements Strategy{
    public void action(){
        System.out.println("strategy1 oepration");
    }
}
class ConcreteStrategy2 implements Strategy{
    public void action(){
        System.out.println("strategy2 oepration");
    }
}
复制代码

  全部代码

复制代码
package com.xingoo.test.design.strategy;
class Context{
    private Strategy strategy;
    public Strategy getStrategy() {
        return strategy;
    }
    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
    public void operation(){
        strategy.action();
    }
}
interface Strategy{
    public void action();
}
class ConcreteStrategy1 implements Strategy{
    public void action(){
        System.out.println("strategy1 oepration");
    }
}
class ConcreteStrategy2 implements Strategy{
    public void action(){
        System.out.println("strategy2 oepration");
    }
}
public class Client {
    public static void main(String[] args) {
        Context ctx = new Context();
        ctx.setStrategy(new ConcreteStrategy1());
        ctx.operation();
        ctx.setStrategy(new ConcreteStrategy2());
        ctx.operation();
    }
}
复制代码

  运行结果

strategy1 oepration
strategy2 oepration

 

本文转自博客园xingoo的博客,原文链接:【设计模式】—— 策略模式Strategy,如需转载请自行联系原博主。
相关文章
|
1月前
|
设计模式 算法
设计模式之 Strategy(策略模式)
设计模式之 Strategy(策略模式)
23 1
|
1月前
|
设计模式 算法 PHP
php设计模式--策略模式(六)
php设计模式--策略模式(六)
11 0
|
4月前
|
设计模式 算法 搜索推荐
设计模式之策略模式
设计模式之策略模式
42 0
|
4月前
|
设计模式 算法 Java
行为型设计模式-策略模式(Strategy Pattern)
行为型设计模式-策略模式(Strategy Pattern)
|
13天前
|
设计模式 算法 Java
Java 设计模式:探索策略模式的概念和实战应用
【4月更文挑战第27天】策略模式是一种行为设计模式,它允许在运行时选择算法的行为。在 Java 中,策略模式通过定义一系列的算法,并将每一个算法封装起来,并使它们可以互换,这样算法的变化不会影响到使用算法的客户。
21 1
|
1月前
|
设计模式 算法 搜索推荐
23种设计模式,策略模式的概念优缺点以及JAVA代码举例
【4月更文挑战第10天】设计模式是软件工程中的一种最佳实践指导,用于解决常见的设计问题。它们被分类为创建型、结构型和行为型模式。其中,策略模式是一种行为型设计模式,旨在定义一系列算法,封装每一个算法,并使它们可互换。策略模式允许算法独立于使用它们的客户端变化
22 1
|
2月前
|
设计模式 算法
策略模式--设计模式
策略模式--设计模式
17 0
|
2月前
|
设计模式 算法 Java
【设计模式】策略模式
【设计模式】策略模式
|
4月前
|
设计模式 算法 自动驾驶
常见的设计模式(模板与方法,观察者模式,策略模式)
随着时间的推移,软件代码越来越庞大,随着而来的就是如何维护日趋庞大的软件系统。在面向对象开发出现之前,使用的是面向过程开发来设计大型的软件程序,面向过程开发将软件分成一个个单独的模块,模块之间使用函数进行组合,最后完成系统的开发,每次需要修改软件,如果不涉及好各个模块的关系,就会导致软件系统难以维护,从而导致软件变得不可使用。面向对象方法用对象模拟问题域中的实体,以对象间的联系刻画实体间联系
68 2
|
4月前
|
设计模式 算法
设计模式 | 策略模式
设计模式 | 策略模式
20 0