简单工厂模式就是考虑如何实例化对象的问题,就是说到底要实例化谁,将来会不会增加实例化对象,比如计算器类中增加开根元素,应该考虑用一个单独的类来创造实例的过程,这就是工厂。下面将利用计算器类举例,解释简单工厂模式:
1.运算符类:
1 package com.lujie; 2 3 public class Operation { 4 private double _numberA=0; 5 private double _numberB=0; 6 7 public void set_numberA(double _numberA) { 8 this._numberA = _numberA; 9 } 10 public void set_numberB(double _numberB) { 11 this._numberB = _numberB; 12 } 13 public double get_numberA() { 14 return _numberA; 15 } 16 public double get_numberB() { 17 return _numberB; 18 } 19 public double getResult() { 20 double result=0; 21 return result; 22 } 23 }
2.利用继承和多态实现代码松耦合:
2.1加法类继承自运算符类:
1 package com.lujie; 2 3 public class OperationAdd extends Operation{ 4 5 public double getResult() { 6 double result =0; 7 result=this.get_numberA()+this.get_numberB(); 8 return result; 9 10 } 11 }
2.2减法类继承自运算符类:
1 package com.lujie; 2 3 public class OperationSub extends Operation{ 4 5 public double getResult() { 6 double result =0; 7 result=this.get_numberA()-this.get_numberB(); 8 return result; 9 10 } 11 }
2.3乘法类继承自运算符类:
1 package com.lujie; 2 3 public class OperationMul extends Operation{ 4 5 public double getResult() { 6 double result =0; 7 if(this.get_numberB()==0) 8 result=this.get_numberA()*this.get_numberB(); 9 return result; 10 11 } 12 }
2.4除法类继承自运算符类:
1 package com.lujie; 2 3 public class OperationDiv extends Operation{ 4 5 public double getResult() { 6 double result =0; 7 try { 8 9 result=this.get_numberA()/this.get_numberB(); 10 11 } catch (Exception e) { 12 System.out.println("除数不能为0!"); 13 } 14 15 return result; 16 } 17 }
3.简单的运算工厂类:
1 class OperationFactory{ 2 public static Operation createOperate(String operate) { 3 4 Operation oper=null; 5 switch (operate) { 6 case "+": 7 oper=new OperationAdd(); 8 break; 9 case "-": 10 oper=new OperationSub(); 11 break; 12 case "*": 13 oper=new OperationMul(); 14 break; 15 case "/": 16 oper=new OperationDiv(); 17 break; 18 } 19 20 return oper; 21 } 22 }
4.工厂模式举例:
1 public static void main(String[] args) { 2 3 Operation oper; 4 oper=OperationFactory.createOperate("/"); 5 oper.set_numberA(1); 6 oper.set_numberB(0); 7 double result=oper.getResult(); 8 System.out.println("结果为:"+result); 9 }
时间: 2024-10-11 04:17:06