标签:key 简单工厂 逻辑 mat block ica pre public date
简单工厂模式,是指通过一个类创建某一类型的实例,根据传入的参数不同,创建对应的实例。这些实例都有一个共同的父类。
将具体的业务逻辑分离封装,客户端只需通过工厂类,来创建所需的实例。后期维护时也只需维护具体的实现类,降低耦合性。利用了java的封装、继承、多态三大特性。
package com.pattern.simpleFactory;
?
public class Operator {
private String numberA;
private String numberB;
?
String printResult;
?
public String getNumberA() {
return numberA;
}
?
public void setNumberA(String numberA) {
this.numberA = numberA;
}
?
public String getNumberB() {
return numberB;
}
?
public void setNumberB(String numberB) {
this.numberB = numberB;
}
?
public String getResult(String operator){
?
return printResult;
}
}
?
package com.pattern.simpleFactory;
?
import java.text.DateFormat;
?
public class Addition extends Operator {
?
public String getResult(String operator) {
DateFormat.getDateInstance();
Double result=Double.parseDouble(getNumberA())+Double.parseDouble(getNumberB());
printResult=result.toString();
return printResult;
?
}
}
?
package com.pattern.simpleFactory;
?
public class Subtraction extends Operator {
public String getResult(String operator) {
Double result = Double.parseDouble(getNumberA()) - Double.parseDouble(getNumberB());
printResult = result.toString();
return printResult;
}
?
}
?
package com.pattern.simpleFactory;
?
public class Multiplication extends Operator{
?
public String getResult(String operator){
Double result=Double.parseDouble(getNumberA())*Double.parseDouble(getNumberB());
printResult=result.toString();
return printResult;
}
?
}
?
package com.pattern.simpleFactory;
?
public class Subtraction extends Operator {
public String getResult(String operator) {
Double result = Double.parseDouble(getNumberA()) - Double.parseDouble(getNumberB());
printResult = result.toString();
return printResult;
}
}
?
package com.pattern.simpleFactory;
?
/*简单工厂模式*/
public class OperationFactory {
Operator operator;
?
public Operator getOperator(String opt) {
switch (opt) {
case "*":
operator = new Multiplication();
break;
case "+":
operator = new Addition();
break;
case "-":
operator = new Subtraction();
break;
case "/":
operator = new Division();
break;
default:
break;
}
return operator;
}
}
?
package com.pattern.simpleFactory;
?
public class Client {
public static void main(String[] args) {
String numberA="23";
String numberB="56";
String opt="/";
/*利用简单工厂生成实例*/
Operator operator =new OperationFactory().getOperator(opt);
operator.setNumberA(numberA);
operator.setNumberB(numberB);
String result =operator.getResult(opt);
System.out.println(result);
?
}
}
?
标签:key 简单工厂 逻辑 mat block ica pre public date
原文地址:https://www.cnblogs.com/yfy-/p/11872276.html