工厂方法模式(Factory Method),定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
运算类:
//运算类 public abstract class Operation { private double numberA=0; private double numberB=0; public double getNumberB() { return numberB; } public void setNumberB(double numberB) { this.numberB = numberB; } public double getNumberA() { return numberA; } public void setNumberA(double numberA) { this.numberA = numberA; } public abstract double GetResult(); } //加法类 public class OperationAdd extends Operation { public double GetResult() { double result=0; result=super.getNumberA()+super.getNumberB(); return result; } } //减法类 public class OperationSub extends Operation { public double GetResult() { double result=0; result=super.getNumberA()-super.getNumberB(); return result; } } //乘法类 public class OperationMul extends Operation { public double GetResult() { double result=0; result=super.getNumberA()*super.getNumberB(); return result; } } //除法类 public class OperationDiv extends Operation { public double GetResult() { double result=0; result=super.getNumberA()/super.getNumberB(); return result; } }
先创建一个工厂接口:
public interface IFactory { Operation CreateOperation(); }
然后加减乘除各建一个具体工厂去实现这个接口:
public class AddFactory implements IFactory { public Operation CreateOperation() { return new OperationAdd(); } } public class SubFactory implements IFactory { public Operation CreateOperation() { return new OperationSub(); } } public class MulFactory implements IFactory { public Operation CreateOperation() { return new OperationMul(); } } public class DivFactory implements IFactory { public Operation CreateOperation() { return new OperationDiv(); } }
客户端实现:
public class Calc { public static void main(String args[]) { IFactory operFactory=new DivFactory(); Operation oper=operFactory.CreateOperation(); oper.setNumberA(1); oper.setNumberB(2); double result=oper.GetResult(); System.out.println(result); } }