软件体系结构设计lym.ppt

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 3.2.8策略模式 strategy模式参与者 Strategy:定义所有支持算法的公共接口。Context使用该接口来调用ConcreteStrategy定义的算法。 ConcreteStrategy:用Strategy接口实现具体算法。 Context:用一个ConcreteStrategy对象来配置。维护一个Strategy对象的引用。可定义一个接口使Stategy访问它的数据。 * 3.2.8策略模式 实例:电子商务网站购物车系统,不同商品不同促销方法 Strategy public abstract class Strategy { public abstract void method(); } ConcreteStrategy public class strategyImplA extends Strategy { public void method() { System.out.println(“A折扣10%); }} public class StrategyImplB extends Strategy { public void method() { System.out.println(“B折扣18%); }} public class StrategyImplC extends Strategy { public void method() { System.out.println(“C折扣60%); }} * 3.2.8策略模式, 实例: Context public class Context { Strategy stra; public Context(Strategy stra) { this.stra = stra; } public void doMethod() { stra.method(); } } Test(client) public class Test { public static void main(String[] args) { Context ctx = new Context(new StrategyImplA()); ctx.doMethod(); ctx = new Context(new StrategyImplB()); ctx.doMethod(); ctx = new Context(new StrategyImplC()); ctx.doMethod(); }} * 3.2.9装饰模式 decorator模式动态地给一个对象添加一些额外的职责。 适用性 在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。 职责是可以撤消的。 当不能采用子类方法进行扩充时。 * 3.2.9装饰模式 decorator模式结构 * 3.2.9装饰模式 decorator模式行为 Decorator 将请求转发给其 Component对象。 在转发请求之前、之后,Decorator 可以选择性地执行一些附加的操作。 * 3.2.9装饰模式 decorator模式参与者 Component:定义对象接口,这些对象可以动态地添加职责。 ConcreteComponent:定义对象,这些对象可以附加一些职责。 Decorator:维持一个指向Component对象的引用,并定义一个与Component接口一致的接口。 ConcreteDecorator:向Component添加职责。 * 3.2.9装饰模式 实例:图形界面工具箱(GUI toolkit) 如一个TextView对象(在窗口中显式文本,默认没有滚动条、边框)。当TextView需要时,可以用附加上滚动条ScrollDecorator。同样方法,可以附加上边框BorderDecorator。 这样的结果可以对TextView使用decorators实现。 * 3.2.9装饰模式 实例:图形界面工具箱(GUI tool

文档评论(0)

1亿VIP精品文档

相关文档