简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。
上示例:
public class Cal {
int num1;
int num2;
public Cal() {
}
public Cal(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
public int getNum1() {
return num1;
}
public void setNum1(int num1) {
this.num1 = num1;
}
public int getNum2() {
return num2;
}
public void setNum2(int num2) {
this.num2 = num2;
}
public int getResult() {
return -1;
}
}
public class CalFactory {
public static Cal createCal(int calType) {
Cal cal = null;
switch (calType) {
case 1 : // +
cal = new Add(3, 4);
break;
case 2:
cal = new Sub(3, 4);
break;
case 3:
cal = new Mul(3, 4);
break;
case 4:
cal = new Div(3, 4);
break;
}
return cal;
}
}
public class Add extends Cal{
public Add() {
}
public Add(int num1, int num2) {
super(num1, num2);
}
public int getResult() {
return num1 + num2;
}
}
public class Sub extends Cal{
public Sub() {
}
public Sub(int num1, int num2) {
super(num1, num2);
}
public int getResult() {
return num1 - num2;
}
}
public class Mul extends Cal{
public Mul() {
}
public Mul(int num1, int num2) {
super(num1, num2);
}
public int getResult() {
return num1 * num2;
}
}
public class Div extends Cal{
public Div() {
}
public Div(int num1, int num2) {
super(num1, num2);
}
public int getResult() {
return num1 / num2;
}
}
public class Demo {
@Test
public void testFactory() {
Cal cal = CalFactory.createCal(1);
cal.num1 = 3;
cal.num2 = 5;
int result = cal.getResult();
System.out.println(result);// 8
}
}
客户端直接使用的是接口,客户端不会和实现发生直接联系,客户端就被接口和实现隔离开来。
简单工厂命名建议:模块名+Factory
而方法名通常命名为:get接口名或是create接口名
简单工厂的核心是选择,不是实现
可以用反射加以改进:
配置文件:
在包reflect里面创建一个db.properties
接口
public interface IDB {
void getConnection();
}
接口实现
public class MySql implements IDB{
@Override
public void getConnection() {
System.out.println("MySql.getConnection");
}
}
工厂
public class DBFactory {
public static IDB createDB() throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
FileInputStream fileInputStream = new FileInputStream("src/reflect/db.properties");
Properties properties = new Properties();
properties.load(fileInputStream);// 加载配置文件
// 获得文件里面className的内容
String classname = properties.getProperty("className");
System.out.println(classname);// 打印内容
Class clazz = Class.forName(classname);// 通过反射获得字节码文件
IDB db = (IDB) clazz.newInstance();// 通过反射获得类对象
return db;
}
}
public class DBDemo {
@Test
public void test() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
IDB db = DBFactory.createDB();
db.getConnection();// 调用对象方法
}
}