Java设计模式--------策略模式

来源:互联网 发布:tensorflow vs spark 编辑:程序博客网 时间:2024/06/10 18:37

      第一次写博客好鸡冻啊。

      Android菜鸟一只,希望大家支持啊。。。今天看了大话设计模式,就把上面的策略模式写了一遍。大牛们不要见笑哈,有误导小伙伴的地方希望小伙伴们积极指出。

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

      基本上策略模式关系到三个类:

Context:Context上下文,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用。

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

ConcreteStrategy:具体算法,封装了具体算法的行为。


      下面是三个类具体的代码:

Context:

public class Context {    private Strategy strategy;    public Context(Strategy strategy) {        this.strategy = strategy;    }    // 上下文接口    public void contextInterface() {        strategy.AlgorithmInterface();    }}

Strategy:

public abstract class Strategy {                 //算法方法public abstract void AlgorithmInterface();}
ConcreteStrategyA:

(当然具体算法的实现可以有很多种)

public class ConcreteStrategyA extends Strategy {@Overridepublic void AlgorithmInterface() {// TODO Auto-generated method stubSystem.out.println("具体算法实现......A");}}
下面来看看客户端具体的实现:

public class Main {private static Context context;public static void main(String[] args) {context = new Context(new ConcreteStrategyA());context.contextInterface();context = new Context(new ConcreteStrategyB());context.contextInterface();context = new Context(new ConcreteStrategyC());context.contextInterface();}}

打印执行结果:

具体算法实现......A
具体算法实现......B
具体算法实现......C




1 0
原创粉丝点击