策略基本解释:
①谋略;手段:讲究策略。 ②与“战略”相对。为实现战略任务而采取的手段。既有稳定性,又有较大的灵活性,随着客观形势的变化而变化。
策略字意解释摘自 http://xh.5156edu.com/html5/z71m35j166307.html
如:去市中心,可以骑自行车,搭公交,搭地铁,驾车
策略模式:接口 + 实现类
如果你的if else像下面这样臃肿,快用策略模式重构它
public class StrategyTest {
public static void main(String[] args) {
String toolName = "Bicycle";
// String toolName = "Bus";
// String toolName = "Metro";
// String toolName = "Car";
timeConsuming(toolName);
}
public static void timeConsuming(String tool) {
if("Bicycle".equals(tool)) {
//这里代替复杂的业务代码
System.out.println("骑自行车到市中心需耗时2小时");
}else if("Bus".equals(tool)) {
System.out.println("搭公交车到市中心需耗时1小时");
}else if("Metro".equals(tool)) {
System.out.println("搭地铁到市中心需耗时50分钟");
}else if("Car".equals(tool)) {
System.out.println("驾车到市中心需耗时45分钟");
}
//else if ...
}
}
创建接口
public interface WalkingTool {
public void timeConsuming();
}
创建实现类
public class Bicycle implements WalkingTool {
public void timeConsuming() {
System.out.println("骑自行车到市中心需耗时2小时");
}
}
public class Bus implements WalkingTool {
public void timeConsuming() {
System.out.println("搭公交车到市中心需耗时1小时");
}
}
public class Car implements WalkingTool {
public void timeConsuming() {
System.out.println("驾车到市中心需耗时45分钟");
}
}
public class Metro implements WalkingTool {
public void timeConsuming() {
System.out.println("搭地铁到市中心需耗时50分钟");
}
}
改造后调用
public class StrategyTest {
public static void main(String[] args) {
//WalkingTool tool = new Bicycle();
WalkingTool tool = new Bus();
//WalkingTool tool = new Metro();
//WalkingTool tool = new Car();
tool.timeConsuming();
}
}
运行结果