什么是简单工厂模式,比如我有一个消息发送的功能,分为kafka消息发送、邮件发送、企业微信发送、boss发送,传统方式是if else做法,但是这要做太不利于扩展了,比我后期我加了其他的短信发送只能不断的if else。
springboot简单工厂实战:
1、在我们的开发当中,现在基本上都是使用springboot框架了,简单工厂自然要整合springboot注解开发
2、定义三个角色:工厂类、抽象产品角色、具体产品角色
3、工厂类BootOrderFactory:BootOrderFactory加上一个@Service注解,spring帮我们创建工厂类
4、抽象产品角色OrderService:定义子类的公共方法,可以是接口或者抽象类,也是子类的公共父类。
5、具体产品角色:在子类SmallProgramImpl和WebsiteImpl里面都加上@Service,spring来创建子类的实例
定义抽象产品角色
public interface MessagePush {
public void sendMesage();
}
定义具体产品角色 boss消息
@Service
public class BossMessageService implements MessagePush {
@Override
public void sendMesage() {
System.out.println("发送boss消息");
}
}
定义具体产品角色 企业邮箱消息
/**
* 企业邮箱
* @author ycs
*
*/
@Service
public class BossWeixinCardMessageService implements MessagePush {
@Override
public void sendMesage() {
System.out.println("发送企业邮箱");
}
}
定义具体产品角色 企业微信消息
/**
* 企业微信
* @author ycs
*
*/
@Service
public class BossWeixinMessageService implements MessagePush {
@Override
public void sendMesage() {
System.out.println("发送企业微信");
}
}
定义具体产品角色 邮件消息
/**
* 邮件发送消息
*/
@Service
public class EmailMessageService implements MessagePush {
@Override
public void sendMesage() {
System.out.println("发送邮件消息");
}
}
定义具体产品角色 kafka消息
/**
* kafka消息
*/
@Service
public class KafkaMessageService implements MessagePush {
@Override
public void sendMesage() {
System.out.println("发送kafka消息");
}
}
定义工厂类
@Service
public class MessagePushFactory {
@Autowired
private BossMessageService bossMessageService;
@Autowired
private BossWeixinCardMessageService bossWeixinCardMessageService;
@Autowired
private BossWeixinMessageService bossWeixinMessageService;
@Autowired
private EmailMessageService emailMessageService;
@Autowired
private KafkaMessageService kafkaMessageService;
public MessagePush sendMesage(Integer type){
switch (type){
case 1:
return bossMessageService;
case 2:
return bossWeixinCardMessageService;
case 3:
return bossWeixinMessageService;
case 4:
return emailMessageService;
case 5:
return kafkaMessageService;
}
return null;
}
}
定义controller访问:
http://localhost:8080/messagePush?type=1
http://localhost:8080/messagePush?type=2
http://localhost:8080/messagePush?type=3
http://localhost:8080/messagePush?type=4
http://localhost:8080/messagePush?type=5
@RestController
public class MessagePushController {
@Autowired
private MessagePushFactory messagePushFactory;
@GetMapping("/messagePush")
public void messagePush(Integer type){
MessagePush messagePush = messagePushFactory.sendMesage(type);
messagePush.sendMesage();
}
}