import com.hys.common.exception.BaseException;
import org.springframework.beans.factory.InitializingBean;
/**
* @Description 抽象类:
* 定义不同策略所要执行的方法,
* 如果执行策略执行了不属于自己的方法,则抛出异常
* @Author Kang Wentai
* @Date 2024/3/17
**/
public abstract class AbstractHander implements InitializingBean {
public void AA() {
throw new BaseException("Method Exception!!");
}
public void BB() {
throw new BaseException("Method Exception!!");
}
}
import com.hys.common.utils.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* @Description 工厂类
* 对索要执行的策略进行注册和调用
* @Author Kang Wentai
* @Date 2024/3/17
**/
public class SimpleFactory {
private static Map<String, AbstractHander> map =new HashMap<>();
public static AbstractHander getHander(String name){
return map.get(name);
}
public static void register(String name, AbstractHander hander){
if(StringUtils.isBlank(name) || hander==null)
return;
map.put(name, hander);
}
import org.springframework.stereotype.Component;
/**
* @Description 实现属于自己的处理方法
* @Author Kang Wentai
* @Date 2024/3/17
**/
@Component
public class MaoMaoHander extends AbstractHander {
@Override
public void AA() {
System.out.println("猫猫");
}
@Override
public void afterPropertiesSet() throws Exception {
SimpleFactory.register("maomao",this);
}
}
import org.springframework.stereotype.Component;
/**
* @Description 实现属于自己的处理方法
* @Author Kang Wentai
* @Date 2024/3/17
**/
@Component
public class NiuNiuHander extends AbstractHander {
@Override
public void BB() {
System.out.println("牛牛");
}
@Override
public void afterPropertiesSet() throws Exception {
SimpleFactory.register("niuniu",this);
}
}
/**
* @Description 测试类
* @Author Kang W.T.
* @CreateTime 2024.3.17. 19:03:00
*/
@SpringBootTest
public class Test {
@org.junit.jupiter.api.Test
public void test(){
AbstractHander niuniu = SimpleFactory.getHander("niuniu");
niuniu.BB();
SimpleFactory.getHander("maomao").AA();
}
}