设计模式——工厂模式
简单工厂模式
/*
简单工厂模式:完全冗余生产,容易混乱
通过一个工厂内实现所有的部件发送消息
*/public class FactorySimple {
//简单工厂模式:内部无该具体类的属性
public void sendMSG(String type,String message) {
if ("Wechat".equals(type)) {
new WechatMSG().sendMsg(message);
}else if ("PhoneMSG".equals(type)) {
new WechatMSG().sendMsg(message);
}else if ("Email".equals(type)) {
new EmailMSG().sendMsg(message);
}else {
//System.out.println("mached error");
throw new NoSuchFieldError("没有该对象实现类");
}
}
}
//
FactorySimple fSimple = new FactorySimple();
fSimple.sendMSG("Wechat", "hello wechat 简单工厂模式");
fSimple.sendMSG("PhoneMSG", "hello phone 简单工厂模式");
fSimple.sendMSG("Email", "hello email 简单工厂模式");
//缺点:增加业务需求,如增加发送邮件,需要修改工厂类中的生产方法
改进:抽象工厂模式
/*
抽象工厂模式:专业化生产,浪费资源,每次都需要新建工厂
通过不同工厂专业化实现特有部件发送消息
*/
public class WechatFactory implements Producer{
@Override
public WechatMSG create() {
// TODO Auto-generated method stub
return new WechatMSG();
}
}
public class PhoneFactory implements Producer{
@Override
public SendMSG create() {
// TODO Auto-generated method stub
return new PhoneMSG();
}
}
WechatFactory wFactory = new WechatFactory();
WechatMSG wMsg = wFactory.create();
wMsg.sendMsg("wechat 抽象工厂模式");
//增加需求,实现+新建对应的工厂类
new PhoneFactory().create().sendMsg("phone 抽象工厂模式");
改进:适配器模式
//对象的适配器模式: 一超多能
public class FactoryAbstract {
private SendMSG sendMSG;
public FactoryAbstract(SendMSG sendMSG) {
this.sendMSG = sendMSG;
}
//方法名称跟实际业务关系
public void sendMSG(String message) {
this.sendMSG.sendMsg(message);
}
}public interface SendMSG {
public void sendMsg(String message);
}
FactoryAbstract fAbstract = new FactoryAbstract(new WechatMSG());
fAbstract.sendMSG("hello wechat");
new FactoryAbstract(new EmailMSG()).sendMSG("hello phone");
//新增发送,只需实例化对象
new FactoryAbstract(new DingDing()).sendMSG("hello dingding");