接口:
public interface Dao {
void add();
}
两个实现类:public class MySQLDao implements Dao{
public void add() {
System.out.println("调用了MySQLDao.add()");
}
}
public class OracleDao implements Dao {
public void add() {
System.out.println("调用了OracleDao.add()");
}
}
工厂类:public class MyFactory {
private static Properties prop = new Properties();
static {
try {
prop.load(MyFactory.class.getResourceAsStream("/impl.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object getObject(String name){
try {
String className = prop.getProperty(name);
Class<?> clazz = Class.forName(className);
Object obj = clazz.getConstructor().newInstance();
return obj;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("创建对象异常");
}
}
}
测试类:public class Test1 {
public static void main(String[] args) {
Dao mysqlDao = (Dao) MyFactory.getObject("mysqlDao");
mysqlDao.add();
Dao oracleDao = (Dao) MyFactory.getObject("oracleDao");
oracleDao.add();
}
}
测试结果:调用了MySQLDao.add()调用了OracleDao.add()
总结:工厂模式,可以理解为:有了很多个工厂方法,自己需要调用哪个类,就调用当前类的工厂方法,获取相应的具体实例。
|
|