(二)策略模式

一.简介

策略模式(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();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容