设计模式——策略模式(基于《大话设计模式》)

在这里插入图片描述
跟简单工厂模式挺像的,不过一个是封装算法(或者说行为),一个是封(创)装(建)对象。
不过书中用的抽象类,我认为略有些不妥,因为算法本质上是一种行为,对行为的抽象应该使用接口才对。
假如说,有一块牛肉,现在我们想吃它,烹饪牛肉,有很多方式,比如炒,煎,煮。

牛肉类:

class Beef{
    private int many;

    @Override
    public String toString() {
        return many +
                "斤牛肉";
    }

    public Beef(int many) {
        this.many = many;
    }
}

烹饪方法类与接口:

interface Cooking{
    void cooking();
}

class CookingBeef0 implements Cooking{
    Beef beef;
    public CookingBeef0(Beef beef){
        this.beef = beef;
    }
    @Override
    public void cooking() {
        System.out.println("炒"+beef);
    }
}

class CookingBeef1 implements Cooking{
    Beef beef;
    public CookingBeef1(Beef beef){
        this.beef = beef;
    }
    @Override
    public void cooking() {
        System.out.println("煎"+beef);
    }
}
class CookingBeef2 implements Cooking{
    Beef beef;
    public CookingBeef2(Beef beef){
        this.beef = beef;
    }
    @Override
    public void cooking() {
        System.out.println("煮"+beef);
    }
}

厨子类

class Cook{
    private Cooking cooking;

    public Cook(Cooking cooking) {
        this.cooking = cooking;
    }
    public void cooking(){
        cooking.cooking();
    }
}

测试代码:

public class testS {
    @Test
    public void testS(){
        Beef beef = new Beef(5);
        Cook cook = new Cook(new CookingBeef0(beef));
        cook.cooking();
        cook = new Cook(new CookingBeef1(beef));
        cook.cooking();
        cook = new Cook(new CookingBeef2(beef));
        cook.cooking();
    }
}

用于解决一些if/else选择判断的。

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读