利用泛型的基础工厂实现MVC三层解耦

package com.gus.factory;

import java.io.FileReader;
import java.util.Properties;

public class BasicFactory {
    private static BasicFactory basicFactory = new BasicFactory();
    private static Properties properties;
    private BasicFactory(){}

    public BasicFactory getBasicFactory() {
        return basicFactory;
    }

    static {
        properties = new Properties();
        try {
            properties.load(new FileReader(BasicFactory.class.getClassLoader().getResource("config.properties").getPath()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public <T> T getInstance(Class<T> clazz) {
        try {
            String cName = clazz.getSimpleName();
            String cImplName = properties.getProperty(cName);
            return (T)Class.forName(cImplName).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}



//在ServiceImpl中只须要这么写:
//CustomerDao customerDao = BasicFactory.getBasicFactory().getInstance(CustomerDao.class);

通常的实现解耦的工厂类:java

package com.gus.factory;

import com.gus.dao.CustomerDao;
import java.io.FileReader;
import java.util.Properties;

//单例模式,须要对外提供方法
//这个工厂提供了dao层和service的解耦
public class CustomerDaoFactory {
    private static CustomerDaoFactory customerDaoFactory = new CustomerDaoFactory();
    private static Properties properties = null;

    private CustomerDaoFactory() {

    }

    public static CustomerDaoFactory getCustomerFactory() {
        return customerDaoFactory;
    }


    //    读取配置文件
    static {
        properties = new Properties();
        try {
            properties.load(new FileReader(CustomerDaoFactory.class.getClassLoader().getResource("config.properties").getPath()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public CustomerDao getCustomerDao() {
        String clazz = properties.getProperty("CustomerDao");
        try {
            return (CustomerDao) Class.forName(clazz).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}


//在service层须要这么写
CustomerDao customerDao = CustomerDaoFactory.getCustomerFactory().getCustomerDao();

service和dao层须要解耦,web层与service层也须要解耦,web

每一个解耦都须要构建一个工厂类。code

还有一种很基础的实现方式:get

public Object getInstance(String clazz) {
        clazz = properties.getProperty(clazz);
        try {
            return  Class.forName(clazz).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

在service层须要这么写:
CustomerDao customerDao = (CustomerDao) BasicFactory.getBasicFactory().getInstance("CustomDao");
不只须要将类名变成String参数传进去,还须要强转一下。

因此,就用第一个吧。io

相关文章
相关标签/搜索