设计模式之策略模式

来源:互联网 发布:php global用法 编辑:程序博客网 时间:2024/06/03 06:37
策略模式定义算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变换不会影响到用户的使用。这些算法完成相同的行为,只不过实现方式不同。以下是策略模式的UML图解以及简单实现:![UML图](http://img.blog.csdn.net/20160826113038128)其中Context负责维护Strategy的引用
class Context{    private Strategy strategy;    public Context(Strategy strategy){        this.strategy=strategy;    }    public void contextInterface(){        strategy.caculate();    }    public void ContextInterfce(String type){        switch(type){            case "strategyA":                strategy=new StrategyA();                strategy.caculate();            case "strategyB":                strategy=new StrategyB();                strategy.caculate();        }    }}abstract class Strategy{    public Object caclulate();}class StrategyA extends Strategy{    public Object caclulate(){        print("A");    }}class StrategyB extends Strategy{    public Object caclulate(){        print("B");    }}class StrategyC extends Strategy{    public Object caclulate(){        print("C");    }}
0 0
原创粉丝点击