Fatory Method 工厂模式根据其具体实现可细化分为下面三种
1. 普通工厂模式
创建一个工厂Class,对实现同一Interface的一批Classes进行实例的创建。类图如下:
代码示例如下:
首先建立一个共同接口
public interface Connector { public boolean connect(String url); }
接着建立两个上面接口的实现类
public class Bluetooch implements Connector { @Override public boolean connect(String url) { System.out.println(String.format("%s.%s called!",this.getClass().getName(),"connect()")); return false; } }public class Httprequest implements Connector { @Override public boolean connect(String url) { System.out.println(String.format("%s.%s called!",this.getClass().getName(),"connect()")); return false; } }之后建立工厂类
public class ConnectFactory { public enum ConnectType{ HTTPREQUEST,BLUETOOCH } public Connector produce(ConnectType type){ Connector production; switch (type){ case BLUETOOCH: production = new Bluetooch(); break; case HTTPREQUEST: production = new Httprequest(); break; default: production = new Httprequest(); } return production; } }使用WorkClass 进行测试:public class WorkClass { public void test() { ConnectFactory connectFactory=new ConnectFactory(); Connector connectorHTTP =connectFactory.produce(ConnectFactory.ConnectType.HTTPREQUEST); connectorHTTP.connect("www.xx.com"); Connector connectorBLUE=connectFactory.produce(ConnectFactory.ConnectType.BLUETOOCH); connectorBLUE.connect("bluetooch://"); } }输出结果:designpattern.creator.Httprequest.connect() called! designpattern.creator.Bluetooch.connect() called!
2. 多工厂方法模式
是对普通工厂方法模式的改良,在普通工厂方法模式中,如果传递的类型不正确,则不能正确创建对象,且枚举也增加开销,而多个工厂方法模式是提供多个工厂方法,分别创建对象,代码如下
public class ConnectFactory {
public Connector produceBluetooch() { return new Bluetooch(); } public Connector produceHttprequest() { return new Httprequest(); }}
测试代码:
public class WorkClass { public void test() {ConnectFactory connectFactory=new ConnectFactory();Connector connectorHttp= connectFactory.produceHttprequest();Connector connectorBLUETOOCH= connectFactory.produceBluetooch();connectorHttp.connect("www.xx.com");
connectorBLUETOOCH.connect("bluetooch://");
}}输出结果:designpattern.creator.Httprequest.connect() called! designpattern.creator.Bluetooch.connect() called!3.静态工厂方法模式将多工厂方法模式进行修改,对方法设置成静态,这样不用创建工厂类public class ConnectFactory { public static Connector SproduceBluetooch() { return new Bluetooch(); } public static Connector SproduceHttprequest() { return new Httprequest(); } }测试类public class WorkClass { public void test() { Connector connectorHTTPS= ConnectFactory.SproduceHttprequest(); Connector connectorBLUETOOCHS= ConnectFactory.SproduceBluetooch(); connectorHTTPS.connect("www.xx.com"); connectorBLUETOOCHS.connect("bluetooch://"); } }输出结果:designpattern.creator.Httprequest.connect() called! designpattern.creator.Bluetooch.connect() called!
结语,工厂模式适合有大量的具有共同的功能接口产品类型需要创建时,可以通过工厂模式进行创建。在以上的三种模式中,第一种如果传入的类型有误,不能正确创建对象,第三种相对于第二种,不需要实例化工厂类,所以,大多数情况下,我们会选用第三种——静态工厂方法模式。