策略模式

策略基本解释:
①谋略;手段:讲究策略。 ②与“战略”相对。为实现战略任务而采取的手段。既有稳定性,又有较大的灵活性,随着客观形势的变化而变化。
策略字意解释摘自 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();
	}
		
}

运行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值