码迷,mamicode.com
首页 > 编程语言 > 详细

java 使用反射技术解耦

时间:2016-10-21 00:34:39      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:

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

 

java 使用反射技术解耦

标签:

原文地址:http://www.cnblogs.com/Westfalen/p/5982822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!