策略模式(Strategy Pattern)

策略模式(Strategy Pattern)


策略模式的组成部分有2部分,一个是Context,也就是提供给外部调用的一个入口;二是一个接口类IStrategy,用于实现各种的策略。下面它的一个简单的类图:

pastedGraphic.pdf


简单代码实现:


/**

*

* @ClassName: IPickUpGrid

* @Description: 以泡妞为例,提供策略的公共方法

* @author xu.dacheng

* @date 2012-12-23 下午4:35:10

*

*/

public interface IPickUpGrid {


/**

* 泡妞的方法

*

* @Title: pickUpGird

* @Description: TODO

* @return void

* @throws

*/

public void pickUpGird();

}

/**

*

* @ClassName: God

* @Description: 上帝为你执行泡妞计划吧

* @author xu.dacheng

* @date 2012-12-23 下午4:37:59

*

*/

public class God {


private IPickUpGrid strategy;

public God(IPickUpGrid strategy){

this.strategy = strategy;

}

public void run(){

this.strategy.pickUpGird();

}

}



/**

*

* @ClassName: Tuidao1

* @Description: 泡妞的具体策略1: 直接推倒...(我承认我的方法有点暴力..)

* @author xu.dacheng

* @date 2012-12-23 下午4:41:31

*

*/

public class Tuidao1 implements IPickUpGrid {


@Override

public void pickUpGird() {

System.out.println("妞!让大爷推倒你吧.....");

}


}


/**

*

* @ClassName: Tuidao2

* @Description: 泡妞比较麻烦 还是直接推倒吧......

* @author xu.dacheng

* @date 2012-12-23 下午4:43:15

*

*/

public class Tuidao2 implements IPickUpGrid {


@Override

public void pickUpGird() {

System.out.println("妞,让大爷再一次推倒你吧.....");

}


}



/**

* @ClassName: CodingFarmer

* @Description: 码农要召唤上帝来泡妞了

* @author xu.dacheng

* @date 2012-12-23 下午4:48:13

*

*/

public class CodingFarmer {


public static void main(String[] args){

God god;

/*叫一个上帝跑出来执行泡妞计划1 推倒....*/

god = new God(new Tuidao1());

god.run();

/*又叫一个上帝跑出来执行泡妞计划2 推倒....*/

god = new God(new Tuidao2());

god.run();

}

}

posted @ 2013-02-18 23:37  shermannnn  阅读(357)  评论(1编辑  收藏  举报