最近买了一本《大话设计模式》,准备好好了解一下设计模式,然后把自己的感受记录一下。
-
什么是简单工厂模式
工厂负责生产,程序里的工厂就是负责生产类的实例,简单工厂实现只需一个类即可,通过公开一个方法,根据传入的相应参数,返回相应的实例,使代码不直接依赖于具体的实现类,从而实现解耦。 -
官方语言比较难以理解,下面就看一下书上的代码以及UML图:
Operation 类(用于接收数字以及拥挤继承的方法)
public class Operation {
private double numA =0;
private double numB =0;
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 double GetResult(){
Double result=0.0;
return result;
}
}
OperationAdd (加法)
public class OperationAdd extends Operation{
public double GetResult(){
double result=0;
result =getNumA()+getNumB();
return result;
}
}
OperationSub (减法)
public class OperationSub extends Operation{
public double GetResult(){
double result=0;
result =getNumA()-getNumB();
return result;
}
}
OperationMul(乘法)
public class OperationMul extends Operation{
public double GetResult(){
double result=0;
result =getNumA()*getNumB();
return result;
}
}
OperationDiv (除法)
public class OperationDiv extends Operation{
public double GetResult(){
double result=0;
result =getNumA()/getNumB();
return result;
}
}
OperationFactory(实现所有功能以及测试)
public class OperationFactory {
public static Operation create(String name){
Operation operation=null;
switch (name){
case "+":
operation=new OperationAdd();
break;
case "-":
operation=new OperationSub();
break;
case '/':
operation=new OperationDiv ();
break;
case '*':
operation=new OperationMul();
break;
}
return operation;
}
public static void main(String[] args) {
Operation operation;
operation=OperationFactory.create("+");
operation.setNumA(1);
operation.setNumB(2);
double result=operation.GetResult();
System.out.println(result);
}
}
简单来说就是你输入运算符号,然后工厂就实例化出合适的对象,通过多台,返回父类的方式实现了计算器的结果