策略模式(Strage Pattern)是将定义的算法家族分别封装起来,让他们之间可以相互替换,从而让算法的变化不会影响到使用算法的用户。
可以避免多重分支的 if... else 或 switch 语句
属于行为型
拿商家搞活动举例:
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();
}
}
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();
}
}
结果:
返现促销
团购促销
原文:https://www.cnblogs.com/lihw-study/p/15221318.html