简单工厂模式(Factory Method):定义一个用于创建对象的接口,让子类决定将哪一个类实例化。Factory Method使一个类的实例化延迟到其子类。
package gof23; public class SimpleFactoryTest { public static void main(String[] args) { Operation oper = null; oper = OperationFactory.createOperate("+"); oper.numA = 2; oper.numB = 0; System.out.println(oper.getResult()); oper = OperationFactory.createOperate("-"); oper.numA = 2; oper.numB = 0; System.out.println(oper.getResult()); oper = OperationFactory.createOperate("*"); oper.numA = 2; oper.numB = 0; System.out.println(oper.getResult()); oper = OperationFactory.createOperate("/"); oper.numA = 2; oper.numB = 0; System.out.println(oper.getResult()); } } class OperationFactory { public static Operation createOperate(String operate) { Operation oper = null; switch(operate) { case "+": oper = new OperationAdd(); break; case "-": oper = new OperationSub(); break; case "*": oper = new OperationMul(); break; case "/": oper = new OperationDiv(); break; } return oper; } } class Operation { protected double numA = 0; protected 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; return result; } } /* * 加法 */ class OperationAdd extends Operation{ @Override public double getResult() { double result = 0; result = numA + numB; return result; } } /* * 减法 */ class OperationSub extends Operation{ @Override public double getResult() { double result = 0; result = numA - numB; return result; } } /* * 乘法 */ class OperationMul extends Operation{ @Override public double getResult() { double result = 0; result = numA * numB; return result; } } /* * 除法 */ class OperationDiv extends Operation{ //注意除数不能为0 @Override public double getResult() { double result = 0; if(Math.abs(numB - 0.0) < 0.00000001) { System.out.println("除数不能为0"); return -1; } result = numA / numB; return result; } }
2.0 2.0 0.0 除数不能为0 -1.0
原文地址:http://blog.csdn.net/hjiam2/article/details/38085723