设计模式-策略模式
在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。
在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。
主要解决:在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护。
JAVA应用:
java.util.Comparator
org.springframework.core.io.Resource
org.springframework.beans.factory.support.InstantiationStrategy
public interface PromotionStrategy { void doPromotion(); }
public class FanXianPromotionStrategy implements PromotionStrategy{ @Override public void doPromotion() { System.out.println("返现促销,返回的金额存放到慕课网用户的余额中"); } }
public class LiJianPromotionStrategy implements PromotionStrategy { @Override public void doPromotion() { System.out.println("立减促销,课程的价格直接减去配置的价格"); } }
public class ManJianPromotionStrategy implements PromotionStrategy{ @Override public void doPromotion() { System.out.println("满减促销,满200-20元"); } }
public class PromotionActivity { private PromotionStrategy promotionStrategy; public PromotionActivity(PromotionStrategy promotionStrategy) { this.promotionStrategy = promotionStrategy; } public void executePromotionStrategy(){ promotionStrategy.doPromotion(); } }
public class Test { public static void main(String[] args) { PromotionActivity promotionActivity618 = new PromotionActivity(new LiJianPromotionStrategy()); PromotionActivity promotionActivity1111 = new PromotionActivity(new FanXianPromotionStrategy()); promotionActivity618.executePromotionStrategy(); promotionActivity1111.executePromotionStrategy(); } }