策略接口:
package com.test.design.stategy;
public interface IStrategy {
//各种策略
public void operate();
}
各种策略:
package com.test.design.stategy;
public class First implements IStrategy {
@Override
public void operate() {
System.out.println("第一种策略...");
}
}
package com.test.design.stategy;
public class Second implements IStrategy {
@Override
public void operate() {
System.out.println("第二种策略...");
}
}
package com.test.design.stategy;
public class Third implements IStrategy {
@Override
public void operate() {
System.out.println("第三种策略...");
}
}
package com.test.design.stategy;
//策略的环境对象
public class Context {
private IStrategy strategy;
public Context(IStrategy strategy){
this.strategy = strategy;
}
public void operate(){
this.strategy.operate();
}
}
package com.test.design.stategy;
//策略的执行者
public class Operator {
public static void main(String[] args) {
//不同环境下执行不同的策略
Context context = new Context(new First());
context.operate();
context = new Context(new Second());
context.operate();
context = new Context(new Third());
context.operate();
}
}
该模式的好处就是:体现了高内聚低耦合的特性。