工厂方法模式
1.定义:
定义一个用于创建对象的接口,让子类决定实例化哪个类。
2.使用场景:
在任何需要生成复杂对象的地方,都可以使用工厂方法模式。复杂对象适合使用工厂模式,用new就可以完成创建的对象无需使用工厂模式。
3.UML图
4.详解:
工厂方法模式,分为普通工厂、多个工厂、静态工厂三种,下面将一一介绍。
首先需要定义一个通用的产品类接口(这里没有按ISender写法),如下:
public interface Sender {
void send();
}
接着需要具体的产品实现类,如下:
public static class MailSender implements Sender {
@Override
public void send() {
System.out.println("this is mail sender!");
}
}
public static class QQSender implements Sender {
@Override
public void send() {
System.out.println("this is qq sender!");
}
}
4.1普通工厂模式
就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建
public static class SendFactory {
public Sender create(String type) {
if ("mail".equals(type)) {
return new MailSender();
} else if ("qq".equals(type)) {
return new QQSender();
} else {
System.out.println("type is not match");
return null;
}
}
}
4.2多个工厂模式
是对普通工厂方法模式的改进,在普通工厂方法模式中,如果传递的字符串出错,则不能正确创建对象,而多个工厂方法模式是提供多个工厂方法,分别创建对象。
public static class MultiFactory {
public MailSender createMail() {
return new MailSender();
}
public QQSender createQQ() {
return new QQSender();
}
}
4.3静态工厂模式
将多个工厂方法模式里的方法置为静态的,不需要创建实例,直接调用即可。
public static class StaticFactory {
public static MailSender createMail() {
return new MailSender();
}
public static QQSender createQQ() {
return new QQSender();
}
}
4.4测试方法:
public static void main(String[] args) {
SendFactory sendFactory = new SendFactory();
sendFactory.create("qq").send();
sendFactory.create("mail").send();
sendFactory.create("bmw");
System.out.println("============below is multi factory================");
MultiFactory multiFactory = new MultiFactory();
multiFactory.createMail().send();
multiFactory.createQQ().send();
System.out.println("=============below is static factory===============");
StaticFactory.createMail().send();
StaticFactory.createQQ().send();
/**
* 输出结果:
this is qq sender!
this is mail sender!
type is not match
============below is multi factory================
this is mail sender!
this is qq sender!
=============below is static factory===============
this is mail sender!
this is qq sender!
*/
}
}