当我们实现某个接口时,可能会有很多种不同的实现方式。这些不同的实现方式通过一定的规则可以随意切换使用时,我们就可以考虑使用策略模式来实现。
1.首先建一个策略接口去继承InitializingBean
package com.example.springbootdemo.strategy;
import com.example.springbootdemo.factory.WaitHandleContext;
import org.springframework.beans.factory.InitializingBean;
/**
* @Author LiXiangrong
* @Description 策略接口
* @Date 2023/03/13 13:08:20
**/
public interface Strategy extends InitializingBean
{
/**
* @Author LiXiangrong
* @Description 要实现的业务方法
* @Date 2023/03/13 13:08:48
* @Return void
**/
void method();
@Override
default void afterPropertiesSet()
{
WaitHandleContext.registry(this);
}
/**
* @Author LiXiangrong
* @Description getType
* @Date 2023/03/13 13:08:43
* @Return java.lang.String
**/
String getType();
}
2.接下来需要创建一个上下文角色类去注册策略。
策略模式的重点是上下文角色类,他封装了对具体策略的调用。上下文角色类中维护着一个抽象角色的引用,高层模块在调用上下文角色类时,通过构造方法或其他方式将具体的策略角色实例赋给该引用,然后调用上下文角色类中的方。通过高层模块在上下文角色类中设置的不同具体策略实例即可执行不同的具体策略。
package com.example.springbootdemo.factory;
import com.example.springbootdemo.strategy.Strategy;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
public class WaitHandleContext
{
private WaitHandleContext()
{
}
private static final Map<String, Strategy> strategyMaps = new ConcurrentHashMap<>();
public static Strategy chooseStrategy(String type)
{
return Optional.ofNullable(strategyMaps.get(type)).orElseThrow(()->new IllegalArgumentException("无对应策略"));
}
public static void registry(Strategy strategy)
{
//不注册重复策略
strategyMaps.putIfAbsent(strategy.getType(), strategy);
System.out.println("策略"+strategy.getType()+"注册成功!");
}
}
评论 (0)