有一種抽象產品——汽車(Car),同時有多種具體的子類產品,如BenzCar,BMWCar,LandRoverCar。類圖如下
作為司機,如果要開其中一種車,比如BenzCar,最直接的做法是直接創建BenzCar的實例,並執行其drive方法,如下
package com.jasongj.client;
import com.jasongj.product.BenzCar;
public class Driver1 {
public static void main(String[] args) {
BenzCar car = new BenzCar();
car.drive();
}
}
此時如果要改為開Land Rover,則需要修改代碼,創建Land Rover的實例並執行其drive方法。這也就意味著任何時候需要換一輛車開的時候,都必須修改客戶端代碼。
一種稍微好點的方法是,通過讀取配置文件,獲取需要開的車,然後創建相應的實例並由父類Car的引用指向它,利用多態執行不同車的drive方法。如下
package com.jasongj.client;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jasongj.product.BMWCar;
import com.jasongj.product.BenzCar;
import com.jasongj.product.Car;
import com.jasongj.product.LandRoverCar;
public class Driver2 {
private static final Logger LOG = LoggerFactory.getLogger(Driver2.class);
public static void main(String[] args) throws ConfigurationException {
XMLConfiguration config = new XMLConfiguration("car.xml");
String name = config.getString("driver2.name");
Car car;
switch (name) {
case "Land Rover":
car = new LandRoverCar();
break;
case "BMW":
car = new BMWCar();
break;
case "Benz":
car = new BenzCar();
break;
default:
car = null;
break;
}
LOG.info("Created car name is {}", name);
car.drive();
}
}
對於Car的使用方而言,只需要通過參數即可指定所需要Car的各類並得到其實例,同時無論使用哪種Car,都不需要修改後續對Car的操作。至此,簡單工廠模式的原型已經形成。如果把上述的邏輯判斷封裝到一個專門的類的靜態方法中,則實現了簡單工廠模式。工廠代碼如下
package com.jasongj.factory;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jasongj.product.BMWCar;
import com.jasongj.product.BenzCar;
import com.jasongj.product.Car;
import com.jasongj.product.LandRoverCar;
public class CarFactory1 {
private static final Logger LOG = LoggerFactory.getLogger(CarFactory1.class);
public static Car newCar() {
Car car = null;
String name = null;
try {
XMLConfiguration config = new XMLConfiguration("car.xml");
name = config.getString("factory1.name");
} catch (ConfigurationException ex) {
LOG.error("parse xml configuration file failed", ex);
}
switch (name) {
case "Land Rover":
car = new LandRoverCar();
break;
case "BMW":
car = new BMWCar();
break;
case "Benz":
car = new BenzCar();
break;
default:
car = null;
break;
}
LOG.info("Created car name is {}", name);
return car;
}
}
調用方代碼如下
package com.jasongj.client;
import com.jasongj.factory.CarFactory1;
import com.jasongj.product.Car;
public class Driver3 {
public static void main(String[] args) {
Car car = CarFactory1.newCar();
car.drive();
}
}
與Driver2相比,所有的判斷邏輯都封裝在工廠(CarFactory1)當中,Driver3不再需要關心Car的實例化,實現了對象的創建和使用的隔離。
當然,簡單工廠模式並不要求一定要讀配置文件來決定實例化哪個類,可以把參數作為工廠靜態方法的參數傳入。
從Driver2和CarFactory1的實現中可以看到,當有新的車加入時,需要更新Driver2和CarFactory1的代碼也實現對新車的支持。這就違反了開閉原則
(Open-Close Principle)。可以利用反射(Reflection)解決該問題。
package com.jasongj.factory;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jasongj.product.Car;
public class CarFactory2 {
private static final Logger LOG = LoggerFactory.getLogger(CarFactory2.class);
public static Car newCar() {
Car car = null;
String name = null;
try {
XMLConfiguration config = new XMLConfiguration("car.xml");
name = config.getString("factory2.class");
} catch (ConfigurationException ex) {
LOG.error("Parsing xml configuration file failed", ex);
}
try {
car = (Car)Class.forName(name).newInstance();
LOG.info("Created car class name is {}", name);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
LOG.error("Instantiate car {} failed", name);
}
return car;
}
}
從上面代碼中可以看到,之後如果需要引入新的Car,只需要在配置文件中指定該Car的完整類名(包括package名),CarFactory2即可通過反射將其實例化。實現了對擴展的開放,同時保證了對修改的關閉。熟悉Spring的讀者應該會想到Spring IoC的實現。
上例中使用反射做到了對擴展開放,對修改關閉。但有些時候,使用類的全名不太方便,使用別名會更合適。例如Spring中每個Bean都會有個ID,引用Bean時也會通過ID去引用。像Apache Nifi這樣的數據流工具,在流程上使用了職責鏈模式,而對於單個Processor的創建則使用了工廠,對於用戶自定義的Processor並不需要通過代碼去注冊,而是使用注解(為了更方便理解下面這段代碼,請先閱讀筆者另外一篇文章《Java系列(一)Annotation(注解)》)。
下面就繼續在上文案例的基礎上使用注解升級簡單工廠模式。
package com.jasongj.factory;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jasongj.annotation.Vehicle;
import com.jasongj.product.Car;
public class CarFactory3 {
private static final Logger LOG = LoggerFactory.getLogger(CarFactory3.class);
private static Map allCars;
static {
Reflections reflections = new Reflections("com.jasongj.product");
Set> annotatedClasses = reflections.getTypesAnnotatedWith(Vehicle.class);
allCars = new ConcurrentHashMap();
for (Class classObject : annotatedClasses) {
Vehicle vehicle = (Vehicle) classObject.getAnnotation(Vehicle.class);
allCars.put(vehicle.type(), classObject);
}
allCars = Collections.unmodifiableMap(allCars);
}
public static Car newCar() {
Car car = null;
String type = null;
try {
XMLConfiguration config = new XMLConfiguration("car.xml");
type = config.getString("factory3.type");
LOG.info("car type is {}", type);
} catch (ConfigurationException ex) {
LOG.error("Parsing xml configuration file failed", ex);
}
if (allCars.containsKey(type)) {
LOG.info("created car type is {}", type);
try {
car = (Car) allCars.get(type).newInstance();
} catch (InstantiationException | IllegalAccessException ex) {
LOG.error("Instantiate car failed", ex);
}
} else {
LOG.error("specified car type {} does not exist", type);
}
return car;
}
}
從上面代碼中可以看到,該工廠會掃描所有被Vehicle注解的Car(每種Car都在注解中聲明了自己的type,可作為該種Car的別名)然後建立起Car別名與具體Car的Class原映射。此時工廠的靜態方法即可根據目標別名實例化對應的Car。
本文所有代碼都可從作者GitHub下載.
簡單工廠模式(Simple Factory Pattern)又叫靜態工廠方法模式(Static FactoryMethod Pattern)。專門定義一個類(如上文中的CarFactory1、CarFactory2、CarFactory3)來負責創建其它類的實例,由它來決定實例化哪個具體類,從而避免了在客戶端代碼中顯式指定,實現了解耦。該類由於可以創建同一抽象類(或接口)下的不同子類對象,就像一個工廠一樣,因此被稱為工廠類。
簡單工廠模式類圖如下所示
簡單工廠模式在JDK中最典型的應用要數JDBC了。可以把關系型數據庫認為是一種抽象產品,各廠商提供的具體關系型數據庫(MySQL,PostgreSQL,Oracle)則是具體產品。DriverManager是工廠類。應用程序通過JDBC接口使用關系型數據庫時,並不需要關心具體使用的是哪種數據庫,而直接使用DriverManager的靜態方法去得到該數據庫的Connection。
package com.jasongj.client;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JDBC {
private static final Logger LOG = LoggerFactory.getLogger(JDBC.class);
public static void main(String[] args) {
Connection conn = null;
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
conn = DriverManager.getConnection("jdbc:hive2://127.0.0.1:10000/default");
PreparedStatement ps = conn.prepareStatement("select count(*) from test.test");
ps.execute();
} catch (SQLException ex) {
LOG.warn("Execute query failed", ex);
} catch(ClassNotFoundException e) {
LOG.warn("Load Hive driver failed", e);
} finally {
if(conn != null ){
try {
conn.close();
} catch (SQLException e) {
// NO-OPT
}
}
}
}
}