如何,实现适配器(Adapter),和多继承(50分)

  • 主题发起人 SupperDog
  • 开始时间
S

SupperDog

Unregistered / Unconfirmed
GUEST, unregistred user!
如题。多谢
 
在使用一个类时,为了使这个类具有更好的复用性,
不能在使用它时增加额外的条件。当客户类使用它
时,当接口不匹配时,如果采用非面向对象的方法
,用硬代码调用这个类,势必会出现大量的重复代
码,出现重复代码的时候就是使用设计模式的时候。
这是可以用一个专门的类来封装这个匹配的过程。
这就是adapter,adapter有两种形式:类适配器
和对象适配器。用类适配器的好处是避免额外的
对象引用,并且可以重新定义被适配类的内容。
对象适配器的好处是可以为被适配类和它所有的
子类提供适配。
 
概念还是了解的,但怎么实现?
Delphi 不能多重继承
 
对于类适配器是多重继承,
先把适配目标抽象出一个接口,
然后使adapter继承被适配类,
实现适配目标借口(delphi的
多重继承)。
对于对象适配器无需多重继承,
只需要在adapter中加一个
被适配类的引用就行了。
 
java的实现方法,pascal这么强大,当然也可以这样做,应该还可以做得更好。
http://www.dotspace.idv.tw/Patterns/Jdon_adapter.htm
 
不知有没有把IAdaptee与IAdaptor关系弄反,
概念忘记得差不多了,从哪个java例子改来的
TContainedObject是没有引用计数的,要自己处理资源问题,可以自己加入
引用计数
program Project1;
{$APPTYPE CONSOLE}
uses
Classes,SysUtils;
type
IAdaptor=interface
['{DD1D6D61-5EAF-11D7-A7B4-0050BA11326A}']
procedure WriteLine;
end;

IAdaptee=interface
['{DD1D6D62-5EAF-11D7-A7B4-0050BA11326A}']
procedure WriteTwoLine;
end;

TBase=class(TContainedObject,IAdaptor)
protected
procedure WriteLine;
public
Constructor Create;overload;
end;

TAdaptor=class(TBase,IAdaptor)
protected
procedure WriteLine;
end;

TAdaptee=class(TInterfacedObject,IAdaptee)
public
procedure WriteTwoLine;
end;

Constructor TBase.Create;
begin
inherited Create(TInterfacedObject.Create);
end;

procedure TBase.WriteLine;
begin
Writeln('-----------------------------------');
end;

procedure TAdaptor.WriteLine;
var
tmp:IAdaptee;
begin
tmp:=Controller as IAdaptee;
tmp.WriteTwoLine;
tmp:=nil;
end;

procedure TAdaptee.WriteTwoLine;
begin
Writeln('-----------------------------------');
Writeln('-----------------------------------');
end;

var
i:IAdaptor;
begin
{ 这个例子没处理资源释放 }
i:=TBase.Create;
i.WriteLine;
ReadLn;
i:=TAdaptor.Create(TAdaptee.Create);
i.WriteLine;
Readln;
end.
 
以“设计模式---用DELPHI表述(帕里的设计模式手册)”为关键在本版查一下。
 
我近来也在学习设计模式,希望多交流。对于VRGL的说法,看起来就比较有功底,可是,
什么叫目标,哪个叫被适配类还请说明清楚。
》对于类适配器是多重继承,
》先把适配目标抽象出一个接口,
》然后使adapter继承被适配类,
》实现适配目标借口(delphi的
》多重继承)。
》对于对象适配器无需多重继承,
》只需要在adapter中加一个
》被适配类的引用就行了。
 
对了,想交流者,请呼QQ78128222,注明设计模式。否则,可不要怪我不客气哟。
:)
 
顶部