工厂设计模式:通过面向对象的三大特性(封装、继承、多态)定义一个用于创建对象的接口,让子类决定实例化那个类,工厂方法使一个类的实例化延迟到其子类
简单案例(加法计算器)
//加减乘除操作工厂
public interface OperationInterface {
public double operate(int a,int b);
}
//创建加减乘除的工厂
public interface FactoryInteface{
public OperationInterface CreateFactory();
}
//加法操作类
public class OperationAdd implements OperationInterface {
@Override
public double operate(int a, int b) {
return a+b;
}
}
//创建加法这一操作的工厂
public class FactoryAdd implements FactoryInteface{
@Override
public OperationInterface CreateFactory() {
return new OperationAdd();
}
}
//主函数调用
public class Factory {
public static void main(String[] arg)
{
FactoryAdd factoryAdd = new FactoryAdd();
OperationInterface add = factoryAdd.CreateFactory();
System.out.println(add.operate(23, 123));
}
}