首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Strategy方式

2012-08-25 
Strategy模式定义了算法家族,分别封装起来,让它们之间可以相互替代,不影响调用?Strategy.javapackage com.

Strategy模式

定义了算法家族,分别封装起来,让它们之间可以相互替代,不影响调用

?

Strategy.java

package com.gary.designpattern.strategy;public interface Strategy {public void hello();}

?

StrategyImplA.java

package com.gary.designpattern.strategy.impl;import com.gary.designpattern.strategy.Strategy;/** * 算法,动作等A * @author gary * */public class StrategyImplA implements Strategy{@Overridepublic void hello(){System.out.println("say hello");}}

?

StrategyImplB.java

package com.gary.designpattern.strategy.impl;import com.gary.designpattern.strategy.Strategy;/** * 算法,动作等B * @author gary * */public class StrategyImplB implements Strategy{@Overridepublic void hello(){System.out.println("say hello in another way");}}

?Content.java

package com.gary.designpattern.strategy;/** * 维护对Strategy的引用 * @author gary * */public class Content {private Strategy strategy;/** * 选择使用哪种 * @param strategy */public Content(Strategy strategy){this.strategy = strategy;}/** * 调用 */public void SayHello(){strategy.hello();}}

?

Test.java

package com.gary.designpattern.strategy;import com.gary.designpattern.strategy.impl.StrategyImplA;import com.gary.designpattern.strategy.impl.StrategyImplB;/** * 测试 * @author gary * */public class Test {public static void main(String[] args) {Strategy strategyA = new StrategyImplA();Content contentA = new Content(strategyA);contentA.SayHello();System.out.println("=======split=====");Strategy strategyB = new StrategyImplB();Content contentB = new Content(strategyB);contentB.SayHello();}}

?

热点排行