工厂模式(Factory Method)
工厂模式分为三种:
1、普通工厂模式
就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建。举例如下:例如,QQ和微信都有发消息的功能,首先,我们创建二者共同的发消息接口:
- public interface SendNotifaction{
-
public void Send();
- }
接着创建实现类:
-
public class QQ implements SendNotifaction{
-
@Override
-
public void Send() {
-
System.out.println("i am a boy!");
-
}
-
}
-
public class WeChat implements SendNotifaction{
-
@Override
-
public void Send() {
-
System.out.println("i am a girl!");
-
}
-
}
最后,我们开始来创建工厂类: -
public class SendNotifactionFactory {
-
public Sender produce(String type) {
-
if ("qq".equals(type)) {
-
return new QQ ();
-
} else if ("wechat".equals(type)) {
-
return new WeChat ();
-
} else {
-
System.out.println("please input right type!");
-
return null;
-
}
-
}
-
}
测试如下: -
public class FactoryTest {
-
public static void main(String[] args) {
-
SendNotifactionFactory factory = new SendNotifactionFactory ();
-
SendNotifaction senderNotifaction = factory.produce("qq");
-
senderNotifaction .Send();
-
}
-
}
控制台打印:i am a boy!
2、多个工厂方法模式
这种模式是对普通工厂方法模式的改进,提供多个工厂方法创建实例.将上面的代码做下修改,改动下SendNotifactionFactory 类就行,如下:
public class SendNotifactionFactory {
public SendNotifactionproduce QQ(){
-
return new QQ ();
-
}
-
public SendNotifactionproduce Wechat(){
-
return new WeChat ();
-
}
-
}
测试类如下: -
public class FactoryTest {
-
public static void main(String[] args) {
-
SendNotifactionFactory factory = new SendNotifactionFactory ();
-
SendNotifaction senderNotifaction = factory.QQ();
-
senderNotifaction .Send();
-
}
-
}
控制台打印:i am a boy!
3、静态工厂方法模式
将上面的多个工厂方法模式里的方法置改为静态的,直接调用即可。 -
public class SendFactory {
-
public static SendNotifactionproduce QQ(){
-
return new QQ();
-
}
-
public static SendNotifactionproduce Wechat(){
-
return new Wechat();
-
}
-
}
-
public class FactoryTest {
-
public static void main(String[] args) {
-
SendNotifaction senderNotifaction = SendNotifactionFactory .QQ();
-
sender.Send();
-
}
-
}
控制台打印:i am a boy!
总结:
工厂模式的应用场景:凡是出现了大量的实例需要创建,并且这些实例具有共同的接口时,就可以运用工厂模式进行创建。在以上的三种模式中,第一种如果传入的参数有误,则不能正确创建对象,第二种需要实例化工厂,浪费没必要的内存性能,所以,大多数情况下,我们会选用第三种——静态工厂方法模式。