一、定义:
工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪个类。工厂方法使一个类的实例化延迟到其子类。
二、示例代码:
//工厂接口,通过实现工厂接口,才创建对应的实例
public interface IFactory {
public Operator createOperator();
}
//加法工厂
public class AddFactory implements IFactory{
@Override
public Operator createOperator() {
return new Addition();
}
}
//除法工厂
public class DivisionFactory implements IFactory {
@Override
public Operator createOperator() {
return new Division();
}
}
//乘法工厂
public class MultipleFactory implements IFactory{
@Override
public Operator createOperator() {
return new Multiplication();
}
}
//减法工厂
public class SubFactory implements IFactory {
@Override
public Operator createOperator() {
return new Subtraction();
}
}
//工厂方法所创建对象的父类
public abstract class Operator {
private String numberA;
private String numberB;
String printResult;
public String getNumberA() {
return numberA;
}
public String getNumberB() {
return numberB;
}
public void setNumberA(String numberA) {
this.numberA = numberA;
}
public void setNumberB(String numberB) {
this.numberB = numberB;
}
public abstract String getResult(String operator);
}
//加法运算类
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;
}
}
//除法运算类
public class Division extends Operator {
public String getResult(String operator) {
if (StringUtils.equals(getNumberB(),"0")){
printResult="除数不能为零0";
}
else {
Integer result = (int) (Double.parseDouble(getNumberA()) / Double.parseDouble(getNumberB()));
printResult = result.toString();
}
return printResult;
}
}
//乘法运算类
public class Multiplication extends Operator {
public String getResult(String operator){
Double result=Double.parseDouble(getNumberA())*Double.parseDouble(getNumberB());
printResult=result.toString();
return printResult;
}
}
//减法运算类
public class Subtraction extends Operator {
public String getResult(String operator) {
Double result = Double.parseDouble(getNumberA()) - Double.parseDouble(getNumberB());
printResult = result.toString();
return printResult;
}
}
//客户端
public class Client {
public static void main(String[] args) throws Exception {
String numberA="23";
String numberB="2";
String opt="2";
/*利用工厂生成实例*/
IFactory factory=new MultipleFactory();
Operator operator = factory.createOperator();
operator.setNumberA(numberA);
operator.setNumberB(numberB);
String result =operator.getResult(opt);
System.out.println(result);
}
}