java 使用反射技术解耦

1.调用的代码 /src/de/test.java

package de;
public class Test {
  public static void main(String[] args) {
   Dao dao = DaoFactory.getInstance().getImpl("impl", Dao.class);
  dao.show();
  }

2.配置文件/src/config/config.properties

  impl=de.DaoImpl1

3.接口和2个实现类 (/src/de/Dao.java,DaoImpl1.java,DaoImpl2.java

package de;
public interface Dao {
    void show();
}
package de;
public class DaoImpl1 implements Dao {
    @Override
    public void show() {
        System.out.println(this.getClass().getSimpleName());
    }
}
package de;
public class DaoImpl2 implements Dao {
    @Override
    public void show() {
        System.out.println(this.getClass().getSimpleName());
    }
}

4.解耦类(单例工厂)

package de;

import java.io.InputStream;
import java.util.Properties;

public class DaoFactory {
    private static DaoFactory instance = new DaoFactory();
    public static DaoFactory getInstance() {
        return instance;
    }

    public <T> T getImpl(String key, Class<T> clazz) {
        try {
            Properties properties = new Properties();
            properties.load(DaoFactory.class.getClassLoader().getResourceAsStream("config/config.properties"));
            return (T) Class.forName(properties.getProperty(key)).newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 

posted @ 2016-10-20 22:09  MarcoReus  阅读(762)  评论(0编辑  收藏  举报