策略模式与机制

在说策略模式之前,我们首先要说下Unix/Linux的接口设计有一句通用“提供机制而不是策略”的格言。 什么是策略,策略有点像战术是具体的东西。而机制像战略是目的。
通俗来说机制是做什么,策略是怎么做。我们知道人要吃饭,但中国人和美国人吃饭不一样。我们用策略模式实现如下:

public class Strategy {
    // 抽象策略
    interface EatStrategy {
        void eatFood();
    }

    static class ChinaEatStrategy implements EatStrategy {
        public void eatFood() {
            System.out.println("用筷子吃中餐");
        }
    }

    static class AmericanEatStrategy implements EatStrategy {
        public void eatFood() {
            System.out.println("用刀叉吃西餐");
        }
    }

    //环境类,提供机制
    static class EatContext {
        private EatStrategy travelStrategy;

        EatContext(String type) {
            switch (type) {
                case "china"://这里可以提供单例
                    this.travelStrategy = new ChinaEatStrategy();
                    break;
                case "american":
                    this.travelStrategy = new AmericanEatStrategy();
                    break;
            }
        }

        public void eat() {
            travelStrategy.eatFood();
        }
    }

    public static void main(String[] args) {
        EatContext context = new EatContext("china");
        context.eat();
        context = new EatContext("american");
        context.eat();
    }
}
输出:
用筷子吃中餐
用刀叉吃西餐

我想说提供机制而不提供策略的下句:策略应该是可选的。

觉得容易理解的话面向对象的23种设计模式点这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值