代理模式

来源:互联网 发布:java类和对象的定义 编辑:程序博客网 时间:2024/06/09 20:27
代理模式:给某一对象提供代理对象,并由代理对象控制具体对象的引用《GOF设计模式》。其实,我们一定要仔细理解代理二字,现实生活中,很多这样的例子,包括 如代理商,生产商和使用用户 间 有一个代理商。有人说,这不是多此一举。其实,有一个中介媒介,在具体的对象设计中,是很有弹性的。  一个公共接口,这个公共接口,必须被代理类和实际工作类 实现。就是说,外界只知道到代理类,而不知道实际工作类的存在。而代理类,在实现的公共接口中,是要调用实际工作的方法,就是说,对工作类的一个引用。COM、COM+很多类似这样的实现模式。 现在,简单用Delphi代码进行实现。 unit Proxy;  {代理模式:在实际使用过程中,让下面这两个类实现 每一个公共接口,这样更灵活}interfacetype    {实际业务工作类}  TRemoteBusiness = class  public    function F1: string;    function F2: string;  end;  {代理类}  TProxy = class  private    FRemoteBusinessObj: TRemoteBusiness;  public    function F1: string;    function F2: string;    constructor create;    destructor Destroy; override;  end;implementation{ TProxy }constructor TProxy.create;begin  FRemoteBusinessObj := TRemoteBusiness.Create;end;destructor TProxy.Destroy;begin  FRemoteBusinessObj.Free;  inherited;end;function TProxy.F1: string;begin  result := FRemoteBusinessObj.F1;end;function TProxy.F2: string;begin  result := FRemoteBusinessObj.F2;end;{ TRemoteBusiness }function TRemoteBusiness.F1: string;begin  result := 'F1 function is Called';end;function TRemoteBusiness.F2: string;begin  result := 'F2 function is Called';end;end. {调用} unit Unit1;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, StdCtrls;type  TForm1 = class(TForm)    Button1: TButton;    Memo1: TMemo;    procedure Button1Click(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;var  Form1: TForm1;implementationuses Proxy;{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);var  Proxy: TProxy;begin  Proxy := TProxy.create;  try    Memo1.Lines.Clear;    Memo1.Lines.Add(Proxy.F1);    Memo1.Lines.Add(Proxy.F2);  finally    proxy.Free;  end;    end;end.   {frm文件} object Form1: TForm1  Left = 291  Top = 136  Width = 422  Height = 209  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 Button1: TButton    Left = 240    Top = 120    Width = 75    Height = 25    Caption = 'Button1'    TabOrder = 0    OnClick = Button1Click  end  object Memo1: TMemo    Left = 16    Top = 16    Width = 297    Height = 89    Lines.Strings = (      'Memo1')    TabOrder = 1  endend

原创粉丝点击