《大话设计模式》之 策略模式 Delphi实现

来源:互联网 发布:老干部,老司机网络意思 编辑:程序博客网 时间:2024/05/24 06:29

{
  策略模式   :用来封装算法,处理各种变法,而简单工厂模式,则是解决创建对象的问题


  策略(Strategy)模式的用意是定义一组算法(algorithms),并将每个算法封装到具有共同接口的独立的类中,

  从而使它们可以相互替换。

  策略模式让算法变化独立于使用它的客户端

 
 使用情景,商场促销,进行商品打折,应用不同的算法,故采用策略模式。
 1。一个抽取类
 2。各种算法的子类
 3。Content,配置类,维护对TCash 类对象的引用
 4。结合简单工厂模拟,降低和客户端驱动的耦合
 
}
unit Strategy;

interface
uses classes, SysUtils;

type
  TCash = class
  protected
    function GetCash(money: double): double; virtual;abstract;
  end;

    {正常收费}
  TCashNormal = class(TCash)
  public
    function GetCash(money: double): double; override;
    constructor create;
  end;

    {打折收费}
  TCashReBate = class(TCash)
  private
    FCashReBete: double;
  public
    function GetCash(money: double): double; override;
    constructor create(CashReBate: double);
  end;

    {返利收费}
  TCashReturn = class(TCash)
  private
    FMoneyContion, FMoneyReturn: Double;
  public
    function GetCash(Money: double): double; override;
    constructor create(MoneyContion, MoneyReturn: Double);
  end;

    {策略模式Content}
  TContent = class
  private
    cash: TCash;
  public
    constructor create(s: string);
    function GetCashValue(Money: double): double;
  end;

 var
   CashContent:TContent;
implementation

{ TCashNormal }

constructor TCashNormal.create;
begin
end;

function TCashNormal.GetCash(money: double): double;
begin
  result := Money;
end;

{ TCashReBate }

constructor TCashReBate.create(CashReBate: double);
begin
  FCashReBete := CashReBate;
end;

function TCashReBate.GetCash(money: double): double;
begin
  result := Money * FCashReBete;
end;

{ TCashReturn }

constructor TCashReturn.create(MoneyContion, MoneyReturn: Double);
begin
  FMoneyContion := MoneyContion;
  FMoneyReturn := MoneyReturn;
end;

function TCashReturn.GetCash(Money: double): double;
begin
  result := 0;
  if FMoneyContion = 0 then Exit;
  result := (Money / FMoneyContion) * FMoneyReturn;
end;

{ TContent }

constructor TContent.create(s: string);
begin
  if s = '正常收费' then
    cash := TCashNormal.create
  else if s = '满300返100' then
    cash:= TCashReturn.create(300, 100)
  else if s = '打八折' then
    cash:= TCashReBate.create(0.8);
end;

function TContent.GetCashValue(Money: double): double;
begin
  if Cash = nil then raise Exception.Create('Cash is nil ,Create Cash Object is Fail!');
  result := Cash.GetCash(Money);
end;

end.

 

{使用}

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    edt_Price: TEdit;
    edt_Qulity: TEdit;
    Button1: TButton;
    Button2: TButton;
    Memo1: TMemo;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label5: TLabel;
    ComboBox1: TComboBox;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
    Total: double;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses Strategy;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  {采用策略模式,只需创建一个TConten对象 }
  CashContent := TContent.create(ComboBox1.Text);
  Total := Total + CashContent.GetCashValue(strtofloatDef(edt_Price.Text, 0) * strtoIntDef(edt_Qulity.Text, 0));
  Memo1.Lines.Add(Format('type:%s, price:%f,qulity:%d,total:%f',
    [
    ComboBox1.Text,
      strtofloatDef(edt_Price.Text, 0),
      strtoIntDef(edt_Qulity.Text, 0),
      Total]));
  Label4.Caption := Format('总价:%f', [Total]);


end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  edt_Price.Text := '0';
  edt_Qulity.Text := '0';
end;

end.

 

 

{窗体文件}

 

object Form1: TForm1
  Left = 644
  Top = 233
  Width = 408
  Height = 361
  Caption = '商场收费系统 '
  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 = 32
    Top = 32
    Width = 36
    Height = 13
    Caption = '价格:'
  end
  object Label2: TLabel
    Left = 32
    Top = 72
    Width = 36
    Height = 13
    Caption = '数量:'
  end
  object Label3: TLabel
    Left = 32
    Top = 128
    Width = 36
    Height = 13
    Caption = '显示:'
  end
  object Label4: TLabel
    Left = 16
    Top = 248
    Width = 337
    Height = 37
    AutoSize = False
    Caption = '总价:'
    Font.Charset = DEFAULT_CHARSET
    Font.Color = clWindowText
    Font.Height = -32
    Font.Name = 'MS Sans Serif'
    Font.Style = []
    ParentFont = False
  end
  object Label5: TLabel
    Left = 32
    Top = 99
    Width = 68
    Height = 13
    Caption = '打折类型:'
  end
  object edt_Price: TEdit
    Left = 88
    Top = 32
    Width = 145
    Height = 21
    TabOrder = 0
  end
  object edt_Qulity: TEdit
    Left = 88
    Top = 64
    Width = 145
    Height = 21
    TabOrder = 1
  end
  object Button1: TButton
    Left = 248
    Top = 32
    Width = 75
    Height = 25
    Caption = '计算'
    TabOrder = 2
    OnClick = Button1Click
  end
  object Button2: TButton
    Left = 248
    Top = 64
    Width = 75
    Height = 25
    Caption = '重置'
    TabOrder = 3
    OnClick = Button2Click
  end
  object Memo1: TMemo
    Left = 80
    Top = 128
    Width = 265
    Height = 97
    TabOrder = 4
  end
  object ComboBox1: TComboBox
    Left = 112
    Top = 96
    Width = 121
    Height = 21
    ItemHeight = 13
    ItemIndex = 0
    TabOrder = 5
    Text = '正常收费'
    Items.Strings = (
      '正常收费'
      '打八折'
      '满300返100')
  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());


        }
    }
}