策略模式_整体的替换算法(把具体算法封装到不同子类,通过实现不同算法的替换)用
/**
* 策略类
* @author maikec
* @date 2019/5/13
*/
public interface Strategy {
/**
* say策略
*/
void say();
}
/**
* @author maikec
* @date 2019/5/13
*/
public class ChineseStrategy implements Strategy {
@Override
public void say() {
System.out.println( "Chinese haha" );
}
}
/**
* @author maikec
* @date 2019/5/13
*/
public class EnglishSayStrategy implements Strategy{
@Override
public void say() {
System.out.println( "English haha" );
}
}
/**
* @author maikec
* @date 2019/5/13
*/
public final class Context {
private final Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public void sayStrategy(){
strategy.say();
}
}
/**
* @author maikec
* @date 2019/5/13
*/
public class StrategyDemo {
public static void main(String[] args) {
if (null != args && args.length > 0){
if ("English".equals( args[0] )){
new Context( new EnglishSayStrategy() ).sayStrategy();
} else {
new Context( new ChineseStrategy() ).sayStrategy();
}
}
}
}
复制代码
附录
github.com/maikec/patt… 个人GitHub设计模式案例
声明
引用该文档请注明出处