用反射改善抽象工厂模式

由于抽象工厂已经在前面介绍过了,这里直接补上如何用反射实现。

模式结构

用反射改善抽象工厂模式_第1张图片

模式实现

引入反射

package com.nchu.abstractFactory;

public class DateAccess {

	private static String assemblyName = "com.nchu.abstractFactory.SqlserverDepartment";
	private static String db = "com.nchu.abstractFactory.SqlserverUser";
	public static IUser createUser() throws Exception{
		Class sqlServerUser = Class.forName(db);
		Object obj = sqlServerUser.newInstance();
		
		return (IUser)obj;
	}
	
	public static IDepartment createDepartment() throws Exception{
		Class sqlServerDepartment = Class.forName(assemblyName);
		Object obj = sqlServerDepartment.newInstance();
		return (IDepartment)obj;
	}
}

测试类

package com.nchu.abstractFactory;

public class Client1 {

	public static void main(String[] args) throws Exception {
		SqlserverDepartment sqlserverDepartment = (SqlserverDepartment) DateAccess.createDepartment();
		SqlserverUser sqlserverUser = (SqlserverUser) DateAccess.createUser();
		
		Department department = new Department();
		User user = new User();
		
		sqlserverDepartment.insert(department);
		sqlserverUser.insert(user);
	}
}

运行结果

用反射改善抽象工厂模式_第2张图片


送给自己的一句话,无痴迷,不成功

你可能感兴趣的:(设计模式,设计模式)