《大话设计模式》之 简单工厂模式 Delphi/C shap /JAVA 实现

时间:2022-02-08 23:57:43

{

计算器的功能实现
 实现工厂设计模式
 通过面向对象的思想,进行设计,所用的编程思想为对象的三大特性:封装,继承,多态
 通过实现一个简单的 计算器的功能(输入两个数,进行加,减,乘,除)

 思想思路:
 1.设计虚拟父类;
 2.子类继承父类
 3. 通过虚拟方法,进行进行重载
 4.工厂类,实例化对象,采用多态

 
}
unit uOperation;

interface

uses Classes, inifiles;

type
  {基础类}
  TOperation = class(Tobject)
  private
    FNumberA: Double;
    FNumberB: Double;
  public
    function GetResult: double; virtual; abstract;
    property NumberA: Double read FNumberA write FNumberA;
    property NumberB: Double read FNumberB write FNumberB;
    constructor create;
    destructor Destroy; override;
  end;

  {加法}
  TAdd = class(TOperation)
  public
    function GetResult: double; override;
  end;

  {减法}
  TSub = class(Toperation)
  public
    function GetResult: double; override;
  end;

  {乘法}
  TMultiple = class(TOperation)
  public
    function GetResult: double; override;
  end;

  {除法}
  TDev = class(TOperation)
  public
    function GetResult: Double; override;
  end;

  {工厂类}

  TOperationFactory = class
  private
    FOpMap: TStringHash;
  public

     {可以 GetOperation 定义为类方法,这样就不用创建TOperationFactory 对象,可以直接使用

     TOperationFactory.GetOperation 但是在本例子中,由于要创建 FOpMap,所有不能定义 类方法,根据情况灵活应用,还有

    简单工厂模式,返回值是父类型}
     function GetOperation(Op: string): TOperation;
    constructor create;
    destructor Destroy; override;

  end;

implementation

{ TOperation }

constructor TOperation.create;
begin

end;

destructor TOperation.Destroy;
begin

  inherited;
end;      

{ TAdd }

function TAdd.GetResult: double;
begin
  result := FNumberA + FNumberB;
end;

{ TSub }

function TSub.GetResult: double;
begin
  result := FNumberA - FNumberB;
end;

{ TMultiple }

function TMultiple.GetResult: double;
begin
  Result := FNumberA * FNumberB;
end;

{ TDev }

function TDev.GetResult: Double;
begin
  Result := 0;
  if FNumberB <> 0 then
    Result := FNumberA / FNumberB;

end;

{ TOperationFactory }

constructor TOperationFactory.create;
begin
  FOpMap := TStringHash.Create;
  FOpMap.Add('+', 1);
  FOpMap.Add('-', 2);
  FOpMap.Add('*', 3);
  FOpMap.Add('/', 4);
end;

destructor TOperationFactory.Destroy;
begin
  FOpMap.Free;
  inherited;
end;

function TOperationFactory.GetOperation(Op: string): TOperation;
begin
  result := nil;
  case FOpMap.ValueOf(Op) of
    1: result := TAdd.create;
    2: result := TSub.create;
    3: result := TMultiple.create;
    4: result := TDev.create;
  end;
end;
end.

 

 

 

{使用}

 

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    Edit2: TEdit;
    Edit3: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Edit4: TEdit;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses uOperation;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  op: TOperation;
  OpFact: TOperationFactory;
begin
  OpFact := TOperationFactory.create;

  op := OpFact.GetOperation(Edit4.Text);
  try
    if op = nil then exit;
    op.NumberA := strtointdef(Edit1.Text, -1);
    op.NumberB := strtointdef(Edit2.Text, -1);
    edit3.Text := FloatToStr(op.GetResult);
  finally
    OPFact.Free;
    OP.Free;
  end;
end;

end.

 

 

窗体文件:

 

 

object Form1: TForm1
  Left = 252
  Top = 218
  Width = 419
  Height = 271
  Caption = 'Form1'
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Label1: TLabel
    Left = 120
    Top = 56
    Width = 60
    Height = 13
    Caption = '第一个数:'
  end
  object Label2: TLabel
    Left = 120
    Top = 88
    Width = 60
    Height = 13
    Caption = '第二个数:'
  end
  object Label3: TLabel
    Left = 120
    Top = 144
    Width = 36
    Height = 13
    Caption = '结果:'
  end
  object Label4: TLabel
    Left = 120
    Top = 114
    Width = 48
    Height = 13
    Caption = '操作符:'
  end
  object Button1: TButton
    Left = 232
    Top = 176
    Width = 75
    Height = 25
    Caption = '计算'
    TabOrder = 0
    OnClick = Button1Click
  end
  object Edit1: TEdit
    Left = 184
    Top = 56
    Width = 121
    Height = 21
    TabOrder = 1
  end
  object Edit2: TEdit
    Left = 184
    Top = 88
    Width = 121
    Height = 21
    TabOrder = 2
  end
  object Edit3: TEdit
    Left = 184
    Top = 144
    Width = 121
    Height = 21
    TabOrder = 3
  end
  object Edit4: TEdit
    Left = 184
    Top = 114
    Width = 121
    Height = 21
    TabOrder = 4
    Text = '+'
  end
end

 

 

//  C Sharp  实现

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OpeartionClass
{
    //抽象父类
    public class TOpeartion
    {
        private Double _NumberA = 0;
        private double _NumberB = 0;

        public Double NumberA
        {
            get { return _NumberA; }
            set { _NumberA = value; }

        }
        public Double NumberB
        {
            get { return _NumberB; }
            set { _NumberB = value; }
        }

        public virtual Double GetResult()
        {
            Double result = 0;
            return result;
        }

    }

    // 加法子类
    public class TAdd : TOpeartion
    {
        public override Double GetResult()
        {
            Double result = 0;
            result = NumberA + NumberB;
            return result;
        }
    }

    // 减法子类
    public class TSub : TOpeartion
    {
        public override Double GetResult()
        {
            Double result = 0;
            result = NumberA - NumberB;
            return result;
        }
    }

    // 乘法子类
    public class TMul : TOpeartion
    {
        public override Double GetResult()
        {
            Double result = 0;
            result = NumberA * NumberB;
            return result;
        }

    }

    // 除法子类
    public class TDev : TOpeartion
    {
        public override double GetResult()
        {
            Double result = 0;
            if (NumberB == 0)
                throw new Exception("除数不能为零!");
            result = NumberA / NumberB;
            return result;
        }
    }


    public class TFactoryCreate
    {
        public static TOpeartion GetOperation(string str)
        {
            TOpeartion opr = null;
            switch (str)
            {
                case "+":
                    opr= new TAdd();
                    break;
                case "-":
                    opr= new TSub();
                    break;
                case "*":
                    opr = new TMul();
                    break;
                case "/":
                    opr= new TDev();
                    break;

            }
            return opr;
        }

    }

}

 

// 调用

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OpeartionClass;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TOpeartion opr;
            opr = TFactoryCreate.GetOperation(textBox3.Text);
            opr.NumberA = Convert.ToInt32(textBox1.Text);
            opr.NumberB = Convert.ToInt32(textBox2.Text);
            textBox4.Text = Convert.ToString(opr.GetResult());


        }
    }
}

 

 

// 窗体文件

 

namespace WindowsFormsApplication1
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.textBox3 = new System.Windows.Forms.TextBox();
            this.textBox4 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(191, 168);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(64, 27);
            this.button1.TabIndex = 0;
            this.button1.Text = "计算";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(93, 23);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(120, 21);
            this.textBox1.TabIndex = 1;
            //
            // textBox2
            //
            this.textBox2.Location = new System.Drawing.Point(93, 50);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(120, 21);
            this.textBox2.TabIndex = 2;
            //
            // textBox3
            //
            this.textBox3.Location = new System.Drawing.Point(93, 77);
            this.textBox3.Name = "textBox3";
            this.textBox3.Size = new System.Drawing.Size(120, 21);
            this.textBox3.TabIndex = 3;
            //
            // textBox4
            //
            this.textBox4.Location = new System.Drawing.Point(93, 104);
            this.textBox4.Name = "textBox4";
            this.textBox4.Size = new System.Drawing.Size(120, 21);
            this.textBox4.TabIndex = 4;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(11, 26);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(77, 12);
            this.label1.TabIndex = 5;
            this.label1.Text = "第一个参数:";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(12, 50);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(77, 12);
            this.label2.TabIndex = 6;
            this.label2.Text = "第二个参数:";
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(12, 80);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(65, 12);
            this.label3.TabIndex = 7;
            this.label3.Text = "运算符号:";
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(11, 113);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(41, 12);
            this.label4.TabIndex = 8;
            this.label4.Text = "结果:";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(296, 225);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox4);
            this.Controls.Add(this.textBox3);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.TextBox textBox3;
        private System.Windows.Forms.TextBox textBox4;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
    }
}

 

 

// JAVA 实现

 

//实现抽象类

 

package OperationFactory;

public abstract class Operation {
   private double NumberA;
   private double NumberB;
  
   public double GetNumberA()
   {
     return NumberA; 
   }
  
   public void SetNumberA(double numbera)
   {
       this.NumberA=numbera;
   }
  
   public double GetNumberB()
   {
       return NumberB;
   }
  
   public void SetNumberB(double numberb)
   {
       this.NumberB=numberb;
   }
  
   public abstract double getresult()throws Exception;
}

 

 

 

//实现子类  加法 OPerationAdd

package OperationFactory;

public class OperationAdd extends Operation {
    @Override
    public double getresult()throws Exception {
        double result = 0;
        result = GetNumberA() + GetNumberB();
        return result;
    }
}

 

//实现子类 除法 OperationDev

 

package OperationFactory;

public class OperationDev extends Operation {

    @Override
    public double getresult() throws Exception {
        double result=0;
        if (GetNumberB()==0)
            throw new Exception("除数不能为0");
        result=GetNumberA()/GetNumberB();
        return result;
    }
}

 

 

//实现子类 乘法 OPerationMul

 

package OperationFactory;

public class OperationMul extends Operation {

    @Override
    public double getresult() throws Exception {
        // TODO Auto-generated method stub
        double result=0;
        result=GetNumberA() * GetNumberB();
        return result;
    }

}

 

 

//实现子类 减法 OperationSub

 

 

package OperationFactory;

public class OperationSub extends Operation {
    @Override
    public double getresult() throws Exception {
        double result = 0;
        result = GetNumberA() - GetNumberB();
        return result;
    }

}

 

 

// 工厂类 OperateFactory

 

 

 

package OperationFactory;

public class OperateFactory {
  public static Operation CreateFactory(String sOperat){
   Operation opr=null;
   if ("+".equalsIgnoreCase(sOperat))
   {
    opr=new OperationAdd(); 
   }else if ("-".equalsIgnoreCase(sOperat))
   {
    opr=new OperationSub();  
   }else if ("*".equalsIgnoreCase(sOperat))
   {
     opr=new OperationMul(); 
   }else if ("/".equalsIgnoreCase(sOperat))
   {
     opr=new OperationDev(); 
   }
  
   return opr;
  }
}

 

 

 

总结: 上面我用三种语言- Delphi 、C Sharp、 JAVA  实现了简单工厂设计模式。它们都是面向对象语言特性,都可以实现其模式设计。这样做的目的是一种尝试,对于初学者来,可以洞悉其中的异同,对于同时需要掌握多门开发语言的人来说,可以做一个比较,印象会更深刻。