策略模式

2016年12月13日

介绍

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

UML图

代码

烹饪接口

    public interface CookOperation {
        void cooking();
    }

厨师的基类中,需要一个烹饪这个技能的实例.

    public abstract class AbstractChef {
        private CookOperation cookOperation;

        public AbstractChef(CookOperation cookOperation) {
            this.cookOperation = cookOperation;
        }

        abstract void doDeliciousFood();

    }

主厨的具体烹饪方式可由调用者进行设置.

    public class MasterChef extends AbstractChef {

        public MasterChef(CookOperation cookOperation) {
            super(cookOperation);
        }

        void doDeliciousFood() {
            // 买菜
            // 洗菜
            // 最后烹饪
            cookOperation.cooking();
        }
    }

采用煮的方式进行烹饪

    public class  BoilCookOperation implements CookOperation {

        public void cooking() {
            // 煮熟食物
        }
    }

uml图中其余类,类似

参考

http://design-patterns.readthedocs.io/zh_CN/latest/structural_patterns/bridge.html

http://www.cnblogs.com/houleixx/archive/2008/02/23/1078877.html

http://blog.csdn.net/janice0529/article/details/44102637

http://blog.csdn.net/shaopeng5211/article/details/8827507