设计模式之策略模式

三、设计模式

10、策略模式(Strategy Pattern)

10.1 定义

策略模式(Strategy Pattern):定义一系列算法,将每一个算法封装起来,并让它们可以相互替换。策略模式让算法独立于使用它的客户而变化,也称为政策模式(Policy)。

10.2 角色分配

  • Context: 环境类
  • Strategy: 抽象策略类
  • ConcreteStrategy: 具体策略类

10.3 结构图

10.4 代码实现

策略接口
public interface Strategy {
	public double getPrice(double standardPrice);

}
算法实现
public class NewCustomerFewStrategy implements Strategy {

	[@Override](https://my.oschina.net/u/1162528)
	public double getPrice(double standardPrice) {
		System.out.println("不打折");
		return standardPrice;
	}

}
public class NewCustomerManyStrategy implements Strategy {

	[@Override](https://my.oschina.net/u/1162528)
	public double getPrice(double standardPrice) {
		System.out.println("九折");
		return standardPrice*0.9;
	}

}
public class OldCustomerFewStrategy implements Strategy {

	[@Override](https://my.oschina.net/u/1162528)
	public double getPrice(double standardPrice) {
		System.out.println("八五折");
		return standardPrice*0.85;
	}

}
public class OldCustomerManyStrategy implements Strategy {

	[@Override](https://my.oschina.net/u/1162528)
	public double getPrice(double standardPrice) {
		System.out.println("八折");
		return standardPrice*0.8;
	}

}
封装接口
public class Context {
	private Strategy strategy;

	public Context(Strategy strategy) {
		super();
		this.strategy = strategy;
	}

	public Strategy getStrategy() {
		return strategy;
	}

	public void setStrategy(Strategy strategy) {
		this.strategy = strategy;
	}

	public void pringPrice(double s) {
		System.out.println("报价:"+strategy.getPrice(s));
	}

}
测试
class Test {

	@org.junit.jupiter.api.Test
	void test() {
		OldCustomerManyStrategy oldCustomerManyStrategy = new OldCustomerManyStrategy();
		Context context = new Context(oldCustomerManyStrategy);
		context.pringPrice(1000);
	}

}
控制台输出

10.5 优点

  • 策略模式提供了对“开闭原则”的完美支持,用户可以在不修改原有系统的基础上选择算法或行为,也可以灵活地增加新的算法或行为。
  • 策略模式提供了管理相关的算法族的办法。
  • 策略模式提供了可以替换继承关系的办法。
  • 使用策略模式可以避免使用多重条件转移语句。

10.6 缺点

  • 客户端必须知道所有的策略类,并自行决定使用哪一个策略类。
  • 策略模式将造成产生很多策略类,可以通过使用享元模式在一定程度上减少对象的数量。

10.7 使用场景

  • Spring框架中,Resource接口,资源访问策略
  • javax.servlet.http.HttpServlet#service()

转载于:https://my.oschina.net/tcwong/blog/3051491

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值