我想这应该是一个容易的因为我必须做错了什么。德尔福IS操作符 - 操作符不适用于此操作数类型
这是我的代码,我想在Delphi做一个策略模式:
unit Pattern;
interface
type
TContext = class;
IStrategy = interface
function Move(c: TContext): integer;
end;
TStrategy1 = class(TInterfacedObject, IStrategy)
public
function Move(c: TContext): integer;
end;
TStrategy2 = class(TInterfacedObject, IStrategy)
public
function Move(c: TContext): integer;
end;
TContext = class
const
START = 5;
private
FStrategy: IStrategy;
public
FCounter: integer;
constructor Create;
function Algorithm(): integer;
procedure SwitchStrategy();
end;
implementation
{ TStrategy1 }
function TStrategy1.Move(c: TContext): integer;
begin
c.FCounter := c.FCounter + 1;
Result := c.FCounter;
end;
{ TStrategy2 }
function TStrategy2.Move(c: TContext): integer;
begin
c.FCounter := c.FCounter - 1;
Result := c.FCounter;
end;
{ TContext }
function TContext.Algorithm: integer;
begin
Result := FStrategy.Move(Self)
end;
constructor TContext.Create;
begin
FCounter := 5;
FStrategy := TStrategy1.Create();
end;
procedure TContext.SwitchStrategy;
begin
if FStrategy is TStrategy1 then
FStrategy := TStrategy2.Create()
else
FStrategy := TStrategy1.Create();
end;
end.
而且如果FStrategy是TStrategy1则是给我:运营商并不适用于这一运算对象类型。 我在这里做错了什么导致这应该工作,因为我从很多Delphi语言参考了解?
详细说明,QueryInterface是一个符号快捷方式,它通过其IID标识接口,Craig将其称为GUID。通过将光标置于'IStrategy = interface'下的空白行并按下CTRL + SHIFT + G来生成一个。 – 2011-03-24 16:17:21
@David,这都是正确的,但即使这样也不会使他的代码工作,因为IID/GUID不匹配类型引用。 – 2011-03-24 16:18:34
@Craig从D2010开始,您可以从Delphi界面中恢复实现对象。 – 2011-03-24 17:19:16