策略模式的核心思想是将算法的定义和使用分离,把一系列算法封装成一个个独立的类,使得它们可以相互替换,从而使程序的扩展性和维护性更强。
// 定义抽象的促销策略接口
interface PromotionStrategy {
void doPromotion();
}
// 具体的促销策略类:满减策略
class FullReducePromotion implements PromotionStrategy {
@Override
public void doPromotion() {
System.out.println("进行满减促销活动,满 300 减 50。");
}
}
// 具体的促销策略类:打折策略
class DiscountPromotion implements PromotionStrategy {
@Override
public void doPromotion() {
System.out.println("进行打折促销活动,商品打 8 折。");
}
}
// 具体的促销策略类:赠品策略
class GiveawayPromotion implements PromotionStrategy {
@Override
public void doPromotion() {
System.out.println("进行赠品促销活动,购买商品赠送小礼品。");
}
}
// 上下文类,持有具体的促销策略实例,并调用其促销方法
class ShoppingContext {
private PromotionStrategy promotionStrategy;
public ShoppingContext(PromotionStrategy promotionStrategy) {
this.promotionStrategy = promotionStrategy;
}
public void executePromotion() {
promotionStrategy.doPromotion();
}
}
// 测试类
public class StrategyPatternExample {
public static void main(String[] args) {
// 使用满减策略进行促销
ShoppingContext fullReduceContext = new ShoppingContext(new FullReducePromotion());
fullReduceContext.executePromotion();
// 使用打折策略进行促销
ShoppingContext discountContext = new ShoppingContext(new DiscountPromotion());
discountContext.executePromotion();
// 使用赠品策略进行促销
ShoppingContext giveawayContext = new ShoppingContext(new GiveawayPromotion());
giveawayContext.executePromotion();
}
}
24万+

被折叠的 条评论
为什么被折叠?



