抽象工厂-比较经典
抽象工厂是一个不错的设计模式,现在利用它实现数据层的高移植性,只需改动?AbstractDaoFactory.properties一个文件:
以下是项目的结构图:
biz业务层,dao数据接口层,mysql和Oracle是数据层的具体实现,factory工厂层,有3个配置文件,命名规则是根据工厂名字命名的,为什么呢,看了代码就知道了。现在业务层只依赖数据接口层和抽象工厂,不和实际的数据层实现发生依赖。在这里面抽象工厂还扮演着模板角色,核心代码如下:
AbstractDaoFactory类:
package org.forever.factory;import java.io.InputStream;import java.util.HashMap;import java.util.Map;import java.util.Properties;public abstract class AbstractDaoFactory {private static AbstractDaoFactory instance; private static Map<String, Object> map = new HashMap<String, Object>();private static Properties properties = new Properties();private static Properties daoproperties = new Properties();private static AbstractDaoFactory getInstance(){if(instance==null){synchronized (AbstractDaoFactory.class) {if(instance==null){String name = AbstractDaoFactory.class.getSimpleName()+".properties";ClassLoader classLoader = AbstractDaoFactory.class.getClassLoader();InputStream inputStream = classLoader.getResourceAsStream(name);try {properties.load(inputStream);String daoFactoryClass = properties.getProperty(AbstractDaoFactory.class.getName());instance = (AbstractDaoFactory)Class.forName(daoFactoryClass).newInstance();daoproperties.load(classLoader.getResourceAsStream(instance.getClass().getSimpleName()+".properties"));} catch (Exception e) {e.printStackTrace();}}}}System.out.println(instance);return instance;}@SuppressWarnings("unchecked")public static <T> T getBean(Class<T> clazz){String className = clazz.getName();if(instance==null){getInstance();}Object obj=map.get(className);if(obj==null){try {obj = Class.forName(daoproperties.getProperty(className)).newInstance();} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e);}map.put(className, obj);}return (T) obj;}}
?
UserBiz类:
package org.forever.biz;import org.forever.dao.UserDao;import org.forever.factory.AbstractDaoFactory;public class UserBiz {private UserDao userDao;public UserBiz() {userDao = AbstractDaoFactory.getBean(UserDao.class);}public static void main(String[] args) {System.out.println(AbstractDaoFactory.getBean(UserDao.class));System.out.println(AbstractDaoFactory.getBean(UserDao.class));System.out.println(AbstractDaoFactory.getBean(UserDao.class));}}
?AbstractDaoFactory.properties:
#org.forever.factory.AbstractDaoFactory=org.forever.factory.MySqlFactory
org.forever.factory.AbstractDaoFactory=org.forever.factory.OracleFactory
MySqlFactory.properties:
org.forever.dao.UserDao=org.forever.dao.mysql.UserDaoImpl
OracleFactory.properties:
org.forever.dao.UserDao=org.forever.dao.oracle.UserDaoImpl
?