简单工厂模式又 叫静态工厂方法模式(Static FactoryMethod Pattern),是通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
public abstract class Operation {
public abstract float getResult(float firstNumber, float secondNumber);
}
//把符号都当做对象处理,实现此接口
public class AddOperation extends Operation {
@Override
public float getResult(float firstNumber, float secondNumber) {
return firstNumber+secondNumber;
}
}
public class SubOperation extends Operation {
@Override
public float getResult(float firstNumber, float secondNumber) {
return firstNumber-secondNumber;
}
}
public class MulOperation extends Operation {
@Override
public float getResult(float firstNumber, float secondNumber) {
return firstNumber*secondNumber;
}
}
public class DivOperation extends Operation {
@Override
public float getResult(float firstNumber, float secondNumber) {
return firstNumber/secondNumber;
}
}
//接下来需要解决的就是对象的创建问题了,既如何根据不同的情况创建不同的对象:我们正好可以通过简单工厂模式实现
public class OperationFactory {
public static Operation getOperation(String quotaFlag){
Operation o = null;
switch (quotaFlag){
case "+" : o = new AddOperation();
case "-" : o = new SubOperation();
case "*" : o = new MulOperation();
case "/" : o = new DivOperation();
default:break;
}
return o;
}
}
//调用:
public class Computer {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("请输入第一个数字:");
float firstNum = in.nextFloat();
System.out.println("请输入第二个数字:");
float secondNum = in.nextFloat();
System.out.println("请输入运算符号:");
String countQuato = in.next();
System.out.println(count(firstNum,secondNum,countQuato));
}
private static float count(float firstNum,float secondNum , String countQuota){
//通过工厂类获取对象
Operation operation = OperationFactory.getOperation(countQuota);
return operation.getResult(firstNum,secondNum);
}
}
简单工厂将对象的创建过程进行了封装,用户不需要知道具体的创建过程,只需要调用工厂类获取对象即可。
这种简单工厂的写法是通过switch-case来判断对象创建过程的。在实际使用过程中,违背了 开放-关闭原则,当然有些情况下可以通过反射调用来弥补这种不足。
网友评论