策略模式简介
策略模式(strategy pattern)是定义一些算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化,不会影响使用算法的客户。
结构
- 1.抽象策略类角色(Abstract Strategy):抽象策略角色一般是接口或者抽象类,定义出具体策略角色所需要的接口。
- 2.具体策略类角色(Concrete Strategy):实现了抽象策略定义的接口,提供具体的算法实现。
- 3.环境角色(Context):持有一个策略类的引用,最终给客户端使用。
UML图

具体实现
例子:商场推出了三种促销活动,买一送一,满1000换购,满30-30,使用策略模式达到随时跟换促销活动场景。
UML图

代码实现
- 抽象策略角色
package com.xxliao.pattern.behavioral.strategy.demo;
/**
* @author xxliao
* @description: 抽象策略接口 -促销活动
* @date 2024/5/27 17:07
*/
public interface Strategy {
void show();
}
- 具体策略角色
package com.xxliao.pattern.behavioral.strategy.demo;
/**
* @author xxliao
* @description: 具体策略类 - 买一送一
* @date 2024/5/27 17:08
*/
public class StrategyOne implements Strategy{
@Override
public void show() {
System.out.println("买一送一。。。");
}
}
package com.xxliao.pattern.behavioral.strategy.demo;
/**
* @author xxliao
* @description: 具体策略类 - 满300 - 30
* @date 2024/5/27 17:09
*/
public class StrategyTwo implements Strategy{
@Override
public void show() {
System.out.println("满300 - 30");
}
}
package com.xxliao.pattern.behavioral.strategy.demo;
/**
* @author xxliao
* @description: 具体策略类 -满1000 可换购200以内的任意商品
* @date 2024/5/27 17:10
*/
public class StrategyThree implements Strategy {
@Override
public void show() {
System.out.println("满1000 可换购200以内的任意商品");
}
}
- 环境角色(上下文)
package com.xxliao.pattern.behavioral.strategy.demo;
/**
* @author xxliao
* @description: 环境角色
* @date 2024/5/27 17:11
*/
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void sale() {
this.strategy.show();
}
}
- 测试客户端
package com.xxliao.pattern.behavioral.strategy.demo;
/**
* @author xxliao
* @description: 策略模式 测试客户端
* @date 2024/5/27 17:12
*/
public class Client {
public static void main(String[] args) {
//
Context context = new Context(new StrategyOne());
context.sale();
}
}
- 测试结果

5万+

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



