简单工厂模式
到底实例化谁,将来是不是增加实例化的对象,比如增加开跟运算,这是很容易变化的地方,应该考虑让一个单独的类来做这个创造实例的过程,,这就是工厂。
public abstract class Cal{
protected double numA ;
protected double numB ;
public double getNumA() {
return numA ;
}
public void setNumA(double numA) {
this.numA = numA;
}
public double getNumB() {
return numB ;
}
public void setNumB(double numB) {
this.numB = numB;
}
public abstract double getResult() throws Exception ;
}
public class OperationAdd extends Cal{
@Override
public double getResult() {
// TODO Auto-generated method stub
return numA + numB;
}
}
//选择到底实例化哪个子类SqlSessionFactory
public class CalFactory {
public static Cal createCal(int calType){
Cal cal = null;
switch (calType) {
case 1://+
oper = new Add();
break;
case 2://-
oper = new Sub();
break;
case 3://*
oper = new Mul();
break;
case 4:///
oper = new Div();
break;
default:
break;
}
return oper;
}
}
public class MainSFactory {
public static void main(String[] args) throws Exception {
Cal cal;
cal= CalFactory. createCal(1);
//Cal cal= new Add();
cal. numA = 1;
cal. numB = 23;
double result =cal.getResult();
System. out.println("The result is : " + result);
}
}
简单工厂的核心是选择而不是实现
简单工厂的改进:
利用反射加载配置文件中设置的数据库:
public abstract class AbstractDB {
public abstract void getConnection();
}
public class MySql extends AbstractDB{
@Override
public void getConnection() {
System.out.println("MySql getConnection");
}
}
public class Oracle extends AbstractDB{
@Override
public void getConnection() {
System.out.println("Oracle getConnection");
}
}
public class DBFactory {
public static AbstractDB getDB(String dbName) {
AbstractDB db = null;
switch(dbName) {
case: "MySql":
db = new MySql();
break;
case: "Oracle":
db = new Oracle();
break;
}
}
}
AbstractDB db = DBFactory.getDB("MySql");
原始的简单工厂有问题:
改进:反射+配置文件
public class DBTest {
public static void main(String[] args) throws Exception {
// AbstractDB db = new MySql();
// db.getConnection();
InputStream inputStream = new FileInputStream("config.properties");
Properties properties = new Properties();
properties.load(inputStream);
String className = properties.getProperty("className");
System.out.println(className);
//com.situ.day22.db.SqlServer
Class clazz = Class.forName("com.situ.day22.db." + className);
AbstractDB db = (AbstractDB) clazz.newInstance();
db.getConnection();
}
}