springboot 设计模式---策略模式

设计模式—策略模式
1.定义接口
public interface payService {
    
    
    void pay();
    void noPay();
}
2.接口实现类
@Service
@Component("Ali")
public class AliPayImpl implements payService{
    
    
    @Override
    public void pay() {
    
    
        System.out.println("支付宝支付");
    }

    @Override
    public void noPay() {
    
    
        System.out.println("支付宝退款");
    }
}





@Service
@Component("UMS")
public class UMSPayImpl implements payService {
    
    
    @Override
    public void pay() {
    
    
        System.out.println("银联支付");
    }

    @Override
    public void noPay() {
    
    
        System.out.println("银联退款");
    }
}





@Service
@Component("WeChat")
public class WeChatPayImpl implements payService{
    
    
    @Override
    public void pay() {
    
    
        System.out.println("微信支付");
    }

    @Override
    public void noPay() {
    
    
        System.out.println("微信退款");
    }
}


@Service
public class PayFactory {
    
    

    @Resource
    Map<String, payService> sts = new ConcurrentHashMap<>(5);

    public payService getChannelService(String channelCodePrefix) {
    
    
        payService strategy = sts.get(channelCodePrefix);
        if (strategy == null) {
    
    
            throw new RuntimeException("no "+channelCodePrefix+" defined");
        }
        return strategy;
    }
}
3.Factory
@Service
public class PayFactory {
    
    

    @Resource
    Map<String, payService> sts = new ConcurrentHashMap<>(5);

    public payService getChannelService(String channelCodePrefix) {
    
    
        payService strategy = sts.get(channelCodePrefix);
        if (strategy == null) {
    
    
            throw new RuntimeException("no "+channelCodePrefix+" defined");
        }
        return strategy;
    }
}
4.测试
@SpringBootTest
class DemoApplicationTests {
    
    

    @Autowired
    private PayFactory payFactory;
    
    @Test
    void contextLoads() {
    
    
        //此处WeChat 对应 impl的 @Component("WeChat")
        payFactory.getChannelService("WeChat").pay();
    }
}

注意:此处WeChat 对应 impl的 @Component(“WeChat”)

猜你喜欢

转载自blog.csdn.net/hsadfdsahfdsgfds/article/details/115026407