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

设计模式——策略模式(基于《大话设计模式》)_第1张图片
跟简单工厂模式挺像的,不过一个是封装算法(或者说行为),一个是封(创)装(建)对象。
不过书中用的抽象类,我认为略有些不妥,因为算法本质上是一种行为,对行为的抽象应该使用接口才对。
假如说,有一块牛肉,现在我们想吃它,烹饪牛肉,有很多方式,比如炒,煎,煮。

牛肉类:

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选择判断的。

你可能感兴趣的:(设计模式,设计模式,面试,笔试)