标签:图片 alt tor int dfa override als lse turn
普通工厂模式:就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建:关系图如下:
1.创建共同的接口
public interface Sender {
public void Send();
}
2.创建该接口的实现类
public class MailSender implements Sender {
@Override
public void Send() {
System.out.println("this is mailsender!");
}
}
public class SmsSender implements Sender {
@Override
public void Send() {
System.out.println("this is sms sender!");
}
}
3.建立工厂类
public class SendFactory {
public Sender produce(String type) {
if ("mail".equals(type)) {
return new MailSender();
} else if ("sms".equals(type)) {
return new SmsSender();
} else {
System.out.println("请输入正确的类型!");
return null;
}
}
}
4.测试
public class FactoryTest {
public static void main(String[] args) {
SendFactory factory = new SendFactory();
Sender sender = factory.produce("sms");
sender.Send();
}
}
输出:this is mailsender!
每天一个设计模式,工厂方法模式(Factory Method)
标签:图片 alt tor int dfa override als lse turn
原文地址:https://www.cnblogs.com/fenghx/p/9497688.html