设计模式-策略模式
定义
策略模式(Strage Pattern)是将定义的算法家族分别封装起来,让他们之间可以相互替换,从而让算法的变化不会影响到使用算法的用户。
可以避免多重分支的 if... else 或 switch 语句
属于行为型
适用场景
- 系统中有很多的类,他们的区别仅仅在于他们的行为(方法实现)不同
- 一个系统需要动态地在几种算法中选择一种
- 需要屏蔽算法规则。
代码示例
拿商家搞活动举例:
- 创建活动类 PromotionActivity
package com.black.design.pattern.strategy;
/**
* 促销活动
* @author black
*
*/
public class PromotionActivity {
private PromotionStrategy promotionStrategy;
public PromotionActivity(PromotionStrategy promotionStrategy) {
this.promotionStrategy = promotionStrategy;
}
public void execute() {
promotionStrategy.doPromotion();
}
}
- 创建促销策略接口类 PromotionStrategy
package com.black.design.pattern.strategy;
/**
* 促销活动接口类
* @author black
*
*/
public interface PromotionStrategy {
/**
* 进行促销
*/
void doPromotion();
}
- 创建返现促销策略实现类
package com.black.design.pattern.strategy;
/**
* 返现
* @author black
*
*/
public class CashBackPromotion implements PromotionStrategy {
public void doPromotion() {
System.out.println("返现促销");
}
}
- 创建团购促销策略实现类
package com.black.design.pattern.strategy;
/**
* 团购
* @author black
*
*/
public class GroupBuyPromotion implements PromotionStrategy {
public void doPromotion() {
System.out.println("团购促销");
}
}
- 测试
package com.black.design.pattern.strategy;
/**
* 策略模式测试类
* @author black
*
*/
public class StrategyTest {
public static void main(String[] args) {
// 返现促销
PromotionStrategy cashBackPromotion = new CashBackPromotion();
// 团购促销
PromotionStrategy groupbyPromotion = new GroupBuyPromotion();
// 返现促销活动
PromotionActivity cashBackActivity = new PromotionActivity(cashBackPromotion);
// 团购促销活动
PromotionActivity groupbyPromotionActivity = new PromotionActivity(groupbyPromotion);
//进行促销
cashBackActivity.execute();
//进行促销
groupbyPromotionActivity.execute();
}
}
结果:
返现促销
团购促销