设计模式-?策略模式

2016-07-28  本文已影响10人  IAmWhoAmI

感觉就是个面向接口编程,
and 和命令模式还有中介者模式差不多,但是又差很多...应该说策略模式是两层的,而命令和中介是三层的。

interface IStrategy{
    public void doSomething();
}
class ConcreteStrategy1 implements IStrategy{

    @Override
    public void doSomething() {
        System.out.println("1");
    }
}
class ConcreteStrategy2 implements IStrategy{
    @Override
    public void doSomething() {
        System.out.println("2");
    }
}
class Context{
    private IStrategy strategy;
    public Context(IStrategy strategy){
        this.strategy=strategy;
    }
    public void execute(){
        strategy.doSomething();
    }
}

public class StrategyTest {
    public static void main(String[] args){
        Context context;
        System.out.println("exe 1");
        context=new Context(new ConcreteStrategy1());
        context.execute();
        System.out.println("exe 2");
        context=new Context(new ConcreteStrategy2());
        context.execute();
    }
}
上一篇下一篇

猜你喜欢

热点阅读