策略模式:
spring框架访问资源属性就采用了策略模式,那么什么是策略模式呢,策略模式为我们解决什么问题呢:
实现某一功能有多种算法或者策略,我们可以根据不同的条件选择不同的算法或者策略,但是如何切换算法而不使得算法和对象耦合,这就要使用策略模式:他定义一系列的算法,将每个算法单独封装起来,并使算法间可以相互替换。由此可以看出策略模式使得算法可独立于使用它的客户而变化。
下面我们参照一个打折算法的实例来了解策略模式:
//策略模式的接口设计:实现这个接口就可以实现打折,但具体的打折策略与该接口无关,而是有具体的实现类来决定打折策略。
DiscountContext这个类在此充当决策者的角色。他决定采用哪种策略进行打折.
spring框架访问资源属性就采用了策略模式,那么什么是策略模式呢,策略模式为我们解决什么问题呢:
实现某一功能有多种算法或者策略,我们可以根据不同的条件选择不同的算法或者策略,但是如何切换算法而不使得算法和对象耦合,这就要使用策略模式:他定义一系列的算法,将每个算法单独封装起来,并使算法间可以相互替换。由此可以看出策略模式使得算法可独立于使用它的客户而变化。
下面我们参照一个打折算法的实例来了解策略模式:
//策略模式的接口设计:实现这个接口就可以实现打折,但具体的打折策略与该接口无关,而是有具体的实现类来决定打折策略。
public interface DiscountStrategy{
//定义一个用于计算打折的方法。
double getDiscount(double originPrice);
}
//VIP打折策略
public class VIPDiscount implements DiscountStrategy{
//重写getDiscount()方法
public double getDiscount(double originPrice){
return originPrice*0.5;
}
}
//折旧打折
public class OldDiscount implements DiscountStrategy{
public double getDiscount(double originPrice){
return originPrice*0.7;
}
}
//以上是两种打折的策略,但是如果客户端代码直接与具体的策略进行耦合,那么客户端将无法实现解耦,因此策略模式提供了一个类,让它为客户端代码决定采用哪种策略:
public class DiscountContext{
//组合一个DiscountStrategy对象
private DiscountStrategy strategy;
public DiscountContext(DiscountStrategy strategy){
this.strategy = strategy;
}
//根据实际使用的DiscountStrategy对象进行打折
public double getDiscountPrice(double price){
//如果strategy为null,系统采用折旧策略打折
if(strategy == null){
strategy = new OldDiscount();
}
return this.strategy.getDiscount(price);
}
//提供切换算法的方法
public void changeDiscount(DiscountStrategy strategy){
this.strategy = strategy
}
}
DiscountContext这个类在此充当决策者的角色。他决定采用哪种策略进行打折.
//测试类
public class StrategyTest{
public static void main(String[] args){
// 客户端没有选择打折策略类
DiscountContext dc = new DiscountContext(null);
double price1 = 79;
// 使用默认的打折策略
System.out.println("79 元的书默认打折后的价格是:" + dc.getDiscountPrice(price1));
// 客户端选择合适的 VIP 打折策略
dc.changeDiscount(new VipDiscount());
double price2 = 89;
// 使用 VIP 打折得到打折价格
System.out.println("89 元的书对 VIP 用户的价格是:" + dc.getDiscountPrice(price2));
}
}