大話設計模式(二)策略模式+簡單工廠
阿新 • • 發佈:2018-12-26
策略模式
定義了演算法,分別封裝起來,讓他們之間可以相互替換,此模式讓演算法的變化不會影響到使用演算法的使用者
/** *定義一個抽象的父類,包含一個抽象的演算法Amethod * / public abstract class Strategy { public abstract void Amethod(); } /** *A類用A的實現去實現演算法A * / public class ConcreteStrategyA extends Strategy{ /** * 演算法A的具體實現 */ @Override public void Amethod() { // TODO Auto-generated method stub } } /** *同樣的可以有B或者C,D演算法 * / 配置一個Context來維護Strategy的引用 public class Context { Strategy strategy; public Context(Strategy strategy) { // TODO Auto-generated constructor stub this.strategy = strategy; } /** * 上下文介面,根據具體的策略物件,呼叫其演算法的方法 */ public void ContextInterface() { strategy.Amethod(); } } /** * 根據不同的需求去例項化不同的演算法 */ Context context = new Context(new ConcreteStrategyA()); Context contextB = new Context(new ConcreteStrategyB()); //例項化物件不同,所以呼叫的演算法就不同
策略模式+簡單工廠
- 加上簡單工廠的話,就是在上下文管理類的地方使用上工廠類,傳入不同的值,就例項化不同的物件。
Strategy strategy; public Context(String type) { // TODO Auto-generated constructor stub switch (type) { case "A": this.strategy = new ConcreteStrategyA(); break; case "B": this.strategy = new ConcreteStrategyB(); default: break; } } /** * 上下文介面,根據具體的策略物件,呼叫其演算法的方法 */ public void ContextInterface() { strategy.Amethod(); } /** * 根據不同的需求去例項化不同的演算法 */ Context contextA = new Context("A"); contextA.ContextInterface(); Context contextB = new Context("B"); contextB.ContextInterface();