设计模式/行为型设计模式
简述
定义一组算法,将每个算法都封装起来,并且使它们之间可以互换
最大特点是使得算法可以在不影响客户端的情况下发生变化,从而改变不同的功能
UML图
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| public interface CatStrategy { void execute(); }
@Slf4j public class DefaultStrategy implements CatStrategy { @Override public void execute() { log.debug(“默认策略 — “); } }
@Slf4j public class ColorStrategy implements CatStrategy { @Override public void execute() { log.debug(“颜色策略 — “); } }
@Slf4j public class CatContext { private CatStrategy catStrategy;
public CatContext(CatStrategy catStrategy) { this.catStrategy = catStrategy; }
public void context() { log.debug(“环境角色 — "); catStrategy.execute(); } }
// 客户端 public class Client { public static void main(String[] args) { CatContext defaultContext = new CatContext(new DefaultStrategy()); defaultContext.context(); CatContext colorContext = new CatContext(new DefaultStrategy()); colorContext.context(); } }
|