关于设计模式中Decorator模式的问题(100分)

  • 主题发起人 南京男生
  • 开始时间

南京男生

Unregistered / Unconfirmed
GUEST, unregistred user!
各位高手,小弟我想请教一下:在Modelmaker 的design patterns 中的Decorator模式中的
那个TTextFilter例子。
如下:
unit Decorate;
interface
type
TTextFilter = class (TTextStream)
private
FOwnsTextStream: Boolean;
FTextStream: TTextStream;
function GetTextStream: TTextStream;
procedure SetTextStream(Value: TTextStream);
protected
function GetEndOfText: Boolean;
override;
public
constructor Create(ATextStream: TTextStream;
AOwnsTextStream: Boolean);
destructor Destroy;
override;
function ReadLine: string;
override;
procedure WriteLine(const Line: string);
override;
property OwnsTextStream: Boolean read FOwnsTextStream write FOwnsTextStream;
property TextStream: TTextStream read GetTextStream write SetTextStream;
end;

TTextStream = class (TObject)
private
protected
function GetEndOfText: Boolean;
virtual;
abstract;
public
function ReadLine: string;
virtual;
abstract;
procedure WriteLine(const Line: string);
virtual;
abstract;
property EndOfText: Boolean read GetEndOfText;
end;

implementation
{
********************************* TTextFilter **********************************
}
constructor TTextFilter.Create(ATextStream: TTextStream;
AOwnsTextStream:
Boolean);
begin
inherited Create;
TextStream := ATextStream;
OwnsTextStream := AOwnsTextStream;
end;

destructor TTextFilter.Destroy;
begin
TextStream := nil;
inherited Destroy;
end;

function TTextFilter.GetEndOfText: Boolean;
begin
Result := TextStream.GetEndOfText;
end;

function TTextFilter.GetTextStream: TTextStream;
begin
Result := FTextStream;
end;

function TTextFilter.ReadLine: string;
begin

Result := TextStream.ReadLine;
end;

procedure TTextFilter.SetTextStream(Value: TTextStream);
begin
if Value <> FTextStream then
begin
if OwnsTextStream then
FTextStream.Free;
FTextStream := Value;
end;
end;

procedure TTextFilter.WriteLine(const Line: string);
begin
TextStream.WriteLine(Line);
end;

{
********************************* TTextStream **********************************
}

end.

请问:例中的
function TTextFilter.ReadLine: string;
begin
Result := TextStream.ReadLine;
end;
TextStream中的ReadLine过程只是一个虚拟抽象的函数,其函数功能实现在哪里定义呢?
是不是如下:
function TTextFilter.ReadLine: string;
begin
{
函数实现体;
}
Result := TextStream.ReadLine;
end;
 
他的代码编译是不能通过的,
TTextStream是个抽象类,
不能实例化,
而GOF的decorator模式中,
基类不是抽象的。
 
to VRGL:确实不能编译;
MM举这个例子那就没多大意义了,为什么又有这个例子呢?小弟我实在水平有限,能否
请哪位大侠举一个用此模式的Delphi例子?是不是基类为非抽象的即可?
 
是的,
基类的函数都是虚的,
但不是抽象的。
 
接受答案了.
 
我想他这个例子是错误的,GoF的Decorator模式不应该进行接口扩展,而仅仅改变其行为,其目的是为了允许自由组合类以防止子类数量暴涨,这个例子显然不具有这些特征。
 
顶部