Java--用简单工厂来改进抽象工厂(反射)

接上一篇抽象工厂,改进方案去除IFactory、SqlServerFactory和AccessFactory三个工厂类取而代之的是DataAccess类,用一个简单工厂模式来实现。

1、DataAccess类

public class DataAccess {
	private static final String db = "SqlServer";
	//private static final String db = "Access";
	public static IUser createUser(){
		IUser result = null;
		switch (db) {
		case "SqlServer":
			result = new SqlServerUser();
			break;
		case "Access":
			result = new AccessUser();
			break;

		default:
			break;
		}
		return result;
	}
	public static IDepartment createDepartment(){
		IDepartment result = null;
		switch (db) {
		case "SqlServer":
			result = new SqlServerDepartment();
			break;
		case "Access":
			result = new AccessDepartment();
			break;

		default:
			break;
		}
		return result;
	}
}
2、测试
public class Test {
	public static void main(String[] args) {
		User user = new User();
		Department department = new Department();
		IUser iu = DataAccess.createUser();
		iu.insert(user);
		iu.getUser(1);
		IDepartment id = DataAccess.createDepartment();
		id.insert(department);
		id.getDepartment(1);
	}
}
3、使用反射机制再优化
public class DataAccess {
	// 包名
	private static final String AccemblyName = "com.test.factory.abstractmethod";
	// 可以替换成Access
	private static final String db = "Access";
	public static IUser createUser(){
		IUser result = null;
		String className = AccemblyName + "." + db +"User";
		Class<?> user = null;
		try {
			user = Class.forName(className);
			result = (IUser)user.newInstance();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}		
		return result;
	}
	public static IDepartment createDepartment(){
		IDepartment result = null;
		String className = AccemblyName + "." + db +"Department";
		Class<?> department = null;
		try {
			department = Class.forName(className);
			result = (IDepartment)department.newInstance();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return result;
	}
}


你可能感兴趣的:(java,设计模式,抽象工厂,反射,简单工厂)