标签:简单 创建对象 复用 inf 而且 业务 pytho instance sig
下面是一个实例结构图及分析
1)首先定义
1)首先定义一个工厂接口
import org.zero01.operation.Operation; public interface Factory { public Operation createOperation() ; }
2)然后是具体的工厂类:
// 加法类工厂 public class AddFactory implements Factory{ public Operation createOperation() { System.out.println("加法运算"); return new Add(); } } // 减法类工厂 public class SubFactory implements Factory{ public Operation createOperation() { System.out.println("减法运算"); return new Sub(); } } ........
3)定义具体的运算类:
public class Add implements Operation{ // 加法计算 public double getResult(double numberA, double numberB) { return numberA + numberB; } } public class Sub implements Operation{ // 减法计算 public double getResult(double numberA, double numberB) { return numberA-numberB; } } public class Mul implements Operation{ // 乘法计算 public double getResult(double numberA, double numberB) { return numberA * numberB; } } public class Div implements Operation { // 除法计算 public double getResult(double numberA, double numberB) throws Exception { if (numberB == 0) { throw new Exception("除数不能为0!"); } return numberA / numberB; } }
4)客户端代码:
public class Client { public static void main(String[] args) throws Exception { // 使用反射机制实例化工厂对象,因为字符串是可以通过变量改变的 Factory addFactory = (Factory) Class.forName("org.zero01.factory.AddFactory").newInstance(); Factory subFactory=(Factory) Class.forName("org.zero01.factory.SubFactory").newInstance(); // 通过工厂对象创建相应的实例对象 Operation add = addFactory.createOperation(); Operation sub = subFactory.createOperation(); System.out.println(add.getResult(1, 1)); System.out.println(sub.getResult(1, 1)); } }
5)结果
2.0 0.0
标签:简单 创建对象 复用 inf 而且 业务 pytho instance sig
原文地址:https://www.cnblogs.com/pghzl-123/p/12005811.html