Java设计模式03-简单工厂

简单工厂并不是一个真正的设计模式,所以没有它的定义。在我的理解中简单工厂就是将原来需要自己初始化对象的地方封装到一个类中达到一定的解耦效果和封装变化的效果。

类图

Java实例

/**
 * 交通工具接口对应的是产品接口
 */
public interface Vehicle {
	void run();
}

/**
 *自行车类,交通工具接口实现类 
 */
public class Bike implements Vehicle{
	public void run() {
		System.out.println("bike running");
	}
}

/**
 * 车类,交通工具借口实现类。
 */
public class Car implements Vehicle{

	public void run() {
		System.out.println("car running");
	}
}

/**
 * 交通工具工厂类
 */
public class VehicleFactory {
	/**
	 * 根据需要生产具体的交通工具的方法
	 * @param vehicleType 交通工具类型
	 * @return 需要 的交通工具
	 */
	public static Vehicle getVehicle(String vehicleType) {
		Vehicle vehicle = null;
		switch(vehicleType) {
			case "bike":
				vehicle = new Bike();
				break;
			case "car":
				vehicle = new Car();
				break;
		}
		return vehicle;	
	}
}

测试类

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter the type of vehicle you need");
		String vehicleType = scanner.next();
		Vehicle vehicle = VehicleFactory.getVehicle(vehicleType);
		vehicle.run();
		scanner.close();
	}
}

控制台
Enter the type of vehicle you need
bike
bike running

以上就是一个简单工厂的实现,这种方法在需要增加具体的交通工具实现类时需要修改具体的代码(swicth case),对此我们可以使用反射的方式来实现。

public class ReflectFactory {
	public static Vehicle greVehicle(String vehicleType) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		String type = "simplefactory."+vehicleType;
		Class<?> clazz = Class.forName(type);
		return (Vehicle)clazz.newInstance();
	}
}

JDK中简单工厂的使用

在JDK中JDBC就是简单工厂的实现

/**
*DriverManager的类成员变量
*使用一个list保存注册的具体Driver
*/
 private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<>();

/**
*遍历Driver List获取具体的Connection并返回。
*/
for(DriverInfo aDriver : registeredDrivers) {
        // If the caller does not have permission to load the driver then
        // skip it.
        if(isDriverAllowed(aDriver.driver, callerCL)) {
            try {
                println("    trying " + aDriver.driver.getClass().getName());
                Connection con = aDriver.driver.connect(url, info);
                if (con != null) {
                    // Success!
                    println("getConnection returning " + aDriver.driver.getClass().getName());
                    return (con);
                }
            } catch (SQLException ex) {
                if (reason == null) {
                    reason = ex;
                }
            }

        } else {
            println("    skipping: " + aDriver.getClass().getName());
        }
    }

源代码 https://github.com/Panici4/DesignPattern/tree/master/simplefactory

posted @ 2018-08-22 13:41  Panic1  阅读(81)  评论(0)    收藏  举报