设计模式——策略模式

策略者模式就是一个功能需求可以有多种策略来进行选择,比如打折,在不同的时间段打折的力度是不同的,按照正常的逻辑我们需要一个个if-else去判断,而策略模式利用开闭原则,抽取出一个接口里面有一个抽象的方法,让不同的策略类去实现这个接口方法,来实现多种策略。在外部策略选择时直接传入选择的策略类即可。

java 复制代码
public interface Strategy {

    void show();

}
java 复制代码
/*
  为春节准备的促销活动A
 */
public class StrategyA implements Strategy {

    public void show() {
        System.out.println("春节活动: 买一送一");
    }

}
java 复制代码
/*
  为中秋准备的促销活动B
 */
public class StrategyB implements Strategy {

    public void show() {
        System.out.println("中秋活动: 满200元减50元");
    }
    
}
java 复制代码
/*
  为国庆准备的促销活动C
 */
public class StrategyC implements Strategy {

    public void show() {
        System.out.println("国庆活动:满1000元加一元换购任意200元以下商品");
    }
    
}
java 复制代码
public class Test {

    public static void main(String[] args) {

        Strategy strategyA = new StrategyA();
        strategyA.show();
        Strategy strategyB = new StrategyB();
        strategyB.show();
        Strategy strategyC = new StrategyC();
        strategyC.show();
    }
}
相关推荐
风筝在晴天搁浅3 天前
美团 手撕策略模式
策略模式
朗迹 - 张伟5 天前
用AI开发QT——Qt与Trae开发环境搭建
开发语言·qt·策略模式
A懿轩A5 天前
Ghostty:告别 Mac 毛坯终端,打造 2026 最丝滑的 Ghostty AI 开发驾驶舱——Claude Code 团队也在用
python·macos·策略模式
二哈赛车手6 天前
新人笔记---多策略搭建策略执行链实现RAG检索后过滤
java·笔记·spring·设计模式·ai·策略模式
geovindu7 天前
go: Strategy Pattern
开发语言·设计模式·golang·策略模式
jimy17 天前
一个夜间期权交易策略的评价
策略模式·程序员创富
harder32110 天前
RMP模式的创新突破
开发语言·学习·ios·swift·策略模式
ximu_polaris10 天前
设计模式(C++)-行为型模式-策略模式
c++·设计模式·策略模式
原来是猿12 天前
线程安全的单例模式
linux·服务器·开发语言·单例模式·策略模式
Mr_linjw13 天前
策略模式简介
策略模式