工厂模式+策略模式

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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值