您的位置:首页 > 其它

【设计模式】21、策略模式

2016-03-09 21:54 288 查看


package com.shejimoshi.behavioral.Strategy;

/**
* 功能:上班的接口
* 时间:2016年3月9日下午8:53:34
* 作者:cutter_point
*/
public interface ToWork
{
/**
* 上班方式
*/
public abstract void workStyle();

}


package com.shejimoshi.behavioral.Strategy;

/**
* 功能:走步上班
* 时间:2016年3月9日下午8:55:15
* 作者:cutter_point
*/
public class WalkingWork implements ToWork
{

@Override
public void workStyle()
{
System.out.println("走步上班");
}

}


package com.shejimoshi.behavioral.Strategy;

/**
* 功能:使用工具去上班
* 时间:2016年3月9日下午8:57:35
* 作者:cutter_point
*/
public class ToolToWork implements ToWork
{

@Override
public void workStyle()
{
System.out.println("使用工具去上班");
}

}


package com.shejimoshi.behavioral.Strategy;

/**
* 功能:选择方式
* 时间:2016年3月9日下午9:15:52
* 作者:cutter_point
*/
public class Select
{
private ToWork tw;

public Select(String type)
{
switch(type)
{
case "步行":
WalkingWork ww = new WalkingWork();
tw = ww;
break;
case "使用工具":
ToolToWork ttw = new ToolToWork();
tw = ttw;
break;
}
}

/**
* 执行相应的策略
*/
public void getResult()
{
tw.workStyle();
}
}


package com.shejimoshi.behavioral.Strategy;

/**
* 功能:定义一系列的算法,把他们一个个封装起来,并且使他们可互相替换。
* 适用:许多相关的类仅仅是行为有差异
*         需要使用一个算法的不同变体
*         算法使用客户不该知道的数据
* 时间:2016年3月9日下午8:49:34
* 作者:cutter_point
*/
public class Test
{
public static void main(String[] args)
{
Select st = new Select("步行");
st.getResult();
Select st2 = new Select("使用工具");
st2.getResult();
}
}


走步上班
使用工具去上班
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: