当前位置: 移动技术网 > IT编程>开发语言>Java > java设计模式之简单工厂模式

java设计模式之简单工厂模式

2019年07月22日  | 移动技术网IT编程  | 我要评论

在编写一个计算器程序时,可以将业务逻辑和显示分离,业务逻辑封装为一个类(封装);如果要新添加一种运算,可以先创建一个operation的基类,然后各种运算从operation类继承,并实现getresult()虚函数,这时添加新的运算只需要派生一个新的类,即不需要之前的运算参与编译。如何让计算器知道我是希望使用哪种运算呢?应该考虑单独的类来做这个创造实例的过程,这就是工厂。创建一个operationfactory类,传入参数,函数createoperate就可以实例化出合适的对象。

java代码如下:

public class operationfactory {
 public static abstract class operation
 {  
  private double _numbera = 0;
  private double _numberb = 0;
  
  public double get_numbera() {
   return _numbera;
  }

  public void set_numbera(double _numbera) {
   this._numbera = _numbera;
  }

  public double get_numberb() {
   return _numberb;
  }

  public void set_numberb(double _numberb) {
   this._numberb = _numberb;
  }
  
  abstract double getresult();
  // todo auto-generated constructor stub
 }
 
 public static class operationadd extends operation
 {
  double getresult() 
  {
   double result = get_numbera() + get_numberb();
   return result;
  }  
 }
 
 public static class operationsub extends operation
 {
  double getresult() {
   double result = get_numbera() - get_numberb();
   return result; 
  }
 }
 
 
 public static operation createoperate(string operate){
  operation oper = null;
  if (operate.equals("+")) {
   oper = new operationadd();
  }
  else if (operate.equals("-")) {
   oper = new operationsub();
  }

  return oper;
 }

 public static void main(string[] args) {
  operation oper;
  oper = operationfactory.createoperate("+");
  oper.set_numbera(1);
  oper.set_numberb(2);
  double result = oper.getresult();
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网