代理模式

代理模式:给某一对象提供代理对象,并由代理对象控制具体对象的引用《GOF设计模式》。

其实,我们一定要仔细理解代理二字,现实生活中,很多这样的例子,包括 如代理商,生产商和使用用户 间 有一个代理商。有人说,这不是多此一举。其实,有一个中介媒介,在具体的对象设计中,是很有弹性的。

  一个公共接口,这个公共接口,必须被代理类和实际工作类 实现。就是说,外界只知道到代理类,而不知道实际工作类的存在。而代理类,在实现的公共接口中,是要调用实际工作的方法,就是说,对工作类的一个引用。COM、COM+很多类似这样的实现模式。

 

现在,简单用Delphi代码进行实现。

 

unit Proxy;
  {代理模式:在实际使用过程中,让下面这两个类实现 每一个公共接口,这样更灵活}
interface
type

    {实际业务工作类}
  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;

interface

uses
  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;

implementation

uses 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
  end
end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值