java 设计模式

java 策略模式

2018-08-08  本文已影响2人  torres9gogogo
//调用者
public class StrategyDemo {

    public static void main(String[] args) {
        //动态的选择某一种算法策略
        Context context1 = new Context(new OperationStrategy1());
        context1.executeStrategy();
        Context context2 = new Context(new OperationStrategy2());
        context2.executeStrategy();
    }
}

//策略接口
interface Strategy {

    void operate();
}

//策略具体算法实现
class OperationStrategy1 implements Strategy {

    @Override
    public void operate() {
        System.out.println("operation1");
    }
}


class OperationStrategy2 implements Strategy {

    @Override
    public void operate() {
        System.out.println("operation2");
    }
}

//使用了某种策略的类。
class Context {

    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;

    }

    public void executeStrategy() {
        strategy.operate();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读