标签:time 就是 mes ssl 成员 技术 程序 put ret
beanDao接口和实现类
public interface BeanDao {
// 模拟add方法
void add();
}
public class BeanDaoImpl implements BeanDao {
@Override
public void add() {
System.out.println("添加bean信息");
}
}
beanService接口和实现类
public interface BeanService {
void add();
}
public class BeanServiceImpl implements BeanService {
BeanDao dao = new BeanDaoImpl();
@Override
public void add() {
dao.add();
}
}
测试类及运行结果
public class Demo {
@Test
public void demo01() {
BeanService service = new BeanServiceImpl();
service.add();
}
}
从代码结构中可以看出: beanService中没有beanDao的耦合度很高, 如果没有BeanDao的实现类, 编译时就会报错
工厂类代码:
public class BeanFactory {
public static Object getInstance(String className) {
try {
Class<?> clazz = Class.forName(className);
Object obj = clazz.newInstance();
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
有了工厂类代码以后我们就可以改造一下beanServiceImpl
public class BeanServiceImpl implements BeanService {
BeanDao dao = (BeanDao) BeanFactory.getInstance("cn.ann.dao.impl.BeanDaoImpl");
@Override
public void add() { dao.add(); }
}
运行结果还是一样的
配置文件bean.properties
beanDao=cn.ann.dao.impl.BeanDaoImpl
beanFactory
public class BeanFactory {
private static Map<String, String> props = new HashMap<>();
static {
try (InputStream is = BeanFactory.class.getClassLoader().
getResourceAsStream("bean.properties")) {
Properties prop = new Properties();
prop.load(is);
Set<String> keys = prop.stringPropertyNames();
keys.forEach((key) -> props.put(key, prop.getProperty(key)));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object getInstance(String key) {
if (props.containsKey(key)) {
try {
Class<?> clazz = Class.forName(props.get(key));
Object obj = clazz.newInstance();
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
throw new RuntimeException("配置文件中不存在该key");
}
}
}
BeanDao dao = (BeanDao) BeanFactory.getInstance("beanDao");
BeanFactory
public class BeanFactory {
private static Map<String, Object> instances = new HashMap<>();
static {
try (InputStream is = BeanFactory.class.getClassLoader().
getResourceAsStream("bean.properties")) {
Properties prop = new Properties();
prop.load(is);
Set<String> keys = prop.stringPropertyNames();
keys.forEach((key) -> {
try {
instances.put(key, Class.forName(prop.getProperty(key)).newInstance());
} catch (Exception e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object getInstance(String key) {
if (instances.containsKey(key)) {
return instances.get(key);
} else {
throw new RuntimeException("配置文件中不存在该key");
}
}
}
本篇到此结束, 这篇文章的重点是关于耦合这方面的, 所以并没有考虑关于线程的问题
本篇代码下载链接: 点击此处 的 spring01-introduce
标签:time 就是 mes ssl 成员 技术 程序 put ret
原文地址:https://www.cnblogs.com/ann-zhgy/p/11776208.html