Context:使用不同的策略的环境,它可以根据自身的条件选择不同的策略实现类来完成所要的操作。它持有一个策略实例的引用,创建具有策略对象的方法也可以由它完成

Strategy:抽象策略,定义每个策略都要实现的策略方法

 

Strategy

package design.pattern.strategy;

public interface Strategy {
    public void run();
}

ConcreteStrateA

package design.pattern.strategy;

public class ConcreteStrateA implements Strategy{

    @Override
    public void run() {
        System.out.println("ConcreteStrateA");
    }

}

ConcreteStrateB

package design.pattern.strategy;

public class ConcreteStrateB implements Strategy{

    @Override
    public void run() {
        System.out.println("ConcreteStrateB");
    }

}

Context

package design.pattern.strategy;

public class Context {
    private Strategy strategy;
    
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }
    
    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }
    
    public void run() {
        strategy.run();
    }
}

Client

package design.pattern.strategy;

public class Client {
    public static void main(String[] args) {
        Context context = new Context(new ConcreteStrateA());
        context.run();
        context.setStrategy(new ConcreteStrateB());
        context.run();
    }
}

 

posted on 2017-10-21 12:29  啊哈咧  阅读(354)  评论(0编辑  收藏  举报