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;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值