美文网首页
(二)策略模式

(二)策略模式

作者: 寻找大海的鱼 | 来源:发表于2019-11-05 20:48 被阅读0次

一.简介

策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。

二.结构

1.策略类Strategy,定义所有支持的算法的公共接口
2.具体策略类,封装了具体的算法或行为,继承于Strategy
3.Context上下文,用一个StrategyContext来配置,维护一个对Strategy对象的引用。

UML用例图如下:

image.png

具体实现如下:

策略接口

public interface Strategy {    //策略接口
    void algorithmMethod();
}

具体策略类A

public class ConcreteStrategyA implements Strategy {    //具体策略类A
    public void algorithmMethod() {
        System.out.println("我是算法A");
    }
}

具体策略类B

public class ConcreteStrategyB implements Strategy {  //具体策略类B
    public void algorithmMethod() {
        System.out.println("我是算法B");
    }
}

具体策略类C

public class ConcreteStrategyC implements Strategy {  //具体策略类C
    public void algorithmMethod() {
        System.out.println("我是算法C");
    }
}

Context上下文

public class StrategyContext {          //Context上下文
    private Strategy strategy;

    public StrategyContext(Strategy strategy) {
        this.strategy = strategy;
    }

    public void contextMethod(){
        strategy.algorithmMethod();
    }
}

客户端代码

public class Test {
    public static void main(String[] args){
        StrategyContext strategyContext = null;
        strategyContext = new StrategyContext(new ConcreteStrategyA());
        strategyContext.contextMethod();

        strategyContext = new StrategyContext(new ConcreteStrategyB());
        strategyContext.contextMethod();

        strategyContext = new StrategyContext(new ConcreteStrategyC());
        strategyContext.contextMethod();
    }
}

相关文章

  • 策略模式

    一、策略模式介绍 二、策略模式代码实例

  • 第5章 -行为型模式-策略模式

    一、策略模式的简介 二、策略模式的优缺点 三、策略模式的应用场景 四、策略模式的实例

  • 第十三章学习策略的教学

    (一)通用学习策略的教学模式 (二)学科学习策略教学模式 (三)交又式学习策略教学模式 三、学习策略的训练 策略的...

  • Java常见设计模式学习(非原创)

    文章大纲 一、策略模式二、观察者模式三、工厂模式四、单例模式五、其他模式六、设计模式总结七、参考文章 一、策略模式...

  • 十三章 学习策略的教学

    学习策略的教学模式 (一)通用学习策略教学模式 (二)学科学习策略教学模式 专门传授语文或数学学科的学习方法与技...

  • 二.策略模式

    1.定义 策略模式:定义了算法族,分别封装起来,让她们可以相互替换。让算法的变化独立于使用算法的客体 2.介绍 应...

  • (二)策略模式

    一.简介 策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化...

  • 11.7设计模式-策略模式-详解

    设计模式-策略模式 策略模式详解 策略模式在android中的实际运用 1.策略模式详解 2.策略模式在andro...

  • 深入浅出设计模式(一)-策略模式

    本文解决问题 什么是策略模式? 策略模式的优缺点以及策略模式解决了什么痛点 策略模式的适用环境 什么是策略模式? ...

  • 策略、工厂模式融合 InitializingBean

    策略、工厂模式融合 InitializingBean 策略、工厂模式分别是什么 策略模式 策略模式是将不同的算法封...

网友评论

      本文标题:(二)策略模式

      本文链接:https://www.haomeiwen.com/subject/wycbvctx.html