Java策略模式的实际应用

策略模式简介:
1、解耦:避免巨型 if-else 分支。
2、可扩展性
3、单一职责原则:每种策略专注自己的业务逻辑

1、定义类型

@Getter
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum StrategyType{

    ManType("ManType", "男的"),

    WomanType("WomanType", "女的"),
}

2、定义策略接口

import java.util.Map;

public interface ITestStrategy{

    ResultData strategyMethod(String a, String b, String c);

}

3、实现策略接口


@Slf4j
public enum TestStrategy implements ITestStrategy{

    ManType {
        @Override
                 public ResultData  strategyMethod(String a, String b, String c){
                        //业务实现
        }
    },

    WomanType{
        @Override
                 public ResultData  strategyMethod(String a, String b, String c){
                        //业务实现
        }
    }
}


4、策略映射类


public class TestContext {

    // 策略接口
    protected ITestStrategy testStrategy;

    // 策略映射
    private static final Map<StrategyType, ITestStrategy > strategyMap = new HashMap<>();

    static {
        strategyMap.put(StrategyType.ManType, TestStrategy .ManType);
        strategyMap.put(StrategyType.WomanType, TestStrategy .WomanType);

    }

    /**
     * 根据类型初始化具体策略
     */
    public TestContext (StrategyType type) {
        this.testStrategy = strategyMap.get(type);
        if (this.testStrategy == null) {
            throw new IllegalArgumentException("不支持的类型:" + type);
        }
    }

    public ResultData strategyMethod(String a, String b, String c) {
        return testStrategy .strategyMethod(a, b, c);
    }

}


6、在别的类进行具体调用

//指定策略类型
TestContext testContext = new TestContext (StrategyType .ManType);
//调用策略方法
ResultData data = testContext .strategyMethod(a,b,c)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容