代理模式主要实现对某一对象的封装,外面对对象的访问需要通过代理来实现对对象的调用。
代理模式主要实现对象与外界的隔离,如源码中的FMM和FGG。
主要参考大话设计模式中的C#源码,整理Delphi源码如下:
------------------------------------------------------------------------------------------------------------------------------
Delphi接口的部分使用原则:
1、接口命名约定 I 起头, 就像类从 T 打头一样.
2、接口都是从 IInterface 继承而来; 若是从根接口继承, 可省略.
3、接口成员只能是方法、属性, 没有字段.
4、接口成员都是公开的, 不需要 private、protected、public、published 等任何访问限制.
5、因为接口只声明、无实现, 也用不到继承与覆盖相关的修饰(virtual、dynamic、abstract、override).
6、一个接口可以从另一个接口继承, 但不能从多个接口继承; 不过 Delphi.Net 已支持接口的多继承了.
7、一个类可以实现多个接口: TMyClass = class(父类, 接口1, 接口2, ...) end;
8、不过实现接口的类有多么丰富, 接口只拥有自己声明的成员.
9、实现接口的类一般继承于 TInterfacedObject, 直接从 TObject 继承会增加一些麻烦而重复的工作.
10、接口在用完后会自释放, 并同时释放拥有它的类; 这很方便, 但同时带来很多问题.
----------------------------------------------------------------------------------------------------------------------------------------------
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TGirl =class
private
{ Private declarations }
FName:string;
public
{ Public declarations }
property Name:string read FName write FName;
end;
IGiveGift = interface
//接口成员全为公开
procedure GiveDolls;
procedure GiveFlowers;
procedure GiveChocolate;
end;
TPerSuit = class(TInterfacedObject,IGiveGift)
private
{ Private declarations }
FMM:TGirl;
public
{ Public declarations }
constructor Create(AMM:TGirl);overload;
procedure GiveDolls;
procedure GiveFlowers;
procedure GiveChocolate;
end;
TProxy = class(TInterfacedObject,IGiveGift)
private
{ Private declarations }
FGG:TPerSuit;
public
{ Public declarations }
constructor Create(AMM:TGirl);overload;
procedure GiveDolls;
procedure GiveFlowers;
procedure GiveChocolate;
end;
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{TPerSuit}
constructor TPerSuit.Create(AMM:TGirl);
begin
FMM := AMM;
end;
procedure TPerSuit.GiveDolls;
begin
Form1.Memo1.Lines.Add(FMM.Name+'送你洋娃娃');
end;
procedure TPerSuit.GiveFlowers;
begin
Form1.Memo1.Lines.Add(FMM.Name+'送你鲜花');
end;
procedure TPerSuit.GiveChocolate;
begin
Form1.Memo1.Lines.Add(FMM.Name+'送你巧克力');
end;
{TProxy}
constructor TProxy.Create(AMM:TGirl);
begin
FGG := TPerSuit.Create(AMM);
end;
procedure TProxy.GiveDolls;
begin
FGG.GiveDolls;
end;
procedure TProxy.GiveFlowers;
begin
FGG.GiveFlowers;
end;
procedure TProxy.GiveChocolate;
begin
FGG.GiveChocolate;
end;
{TForm1}
procedure TForm1.Button1Click(Sender: TObject);
var
vMM:TGirl;
vDL:TProxy;
begin
vMM := TGirl.Create;
vMM.Name:='TT';
vDL := TProxy.Create(vMM);
vDL.GiveDolls;
vDL.GiveFlowers;
vDL.GiveChocolate;
end;
end.