インタフェースの委任実装(インタフェース経由)

6962 ワード

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  IBaseInterface = interface
    procedure Buy(s : string);
  end;

  IMyInterface = interface(IBaseInterface)
    procedure Sell(s: string);
  end;

  TBaseClass = class(TInterfacedObject, IMyInterface)
    procedure Buy(s : string);
    procedure Sell(s: string);
  end;

  TMyClass = class(TInterfacedObject, IBaseInterface)
  private
    ITest: IBaseInterface;
  protected
    property service: IBaseInterface read ITest implements IBaseInterface;
  public
    constructor Create(AClass: TClass);
    destructor Destory(AClass: TClass);

  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TBaseClass }

procedure TBaseClass.Buy(s: string);
begin
  ShowMessage('Buy ' + s);
end;

procedure TBaseClass.Sell(s: string);
begin
  ShowMessage('Sell ' + s);
end;

{ TMyClass }

constructor TMyClass.Create(AClass: TClass);
var
  baseObj: IMyInterface;
begin
  baseObj := TBaseClass(AClass.NewInstance);
  ITest := baseObj;
end;

destructor TMyClass.Destory(AClass: TClass);
begin
  ITest := nil;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  test: TMyClass;
begin
  try
    test := TMyClass.Create(TBaseClass);
    test.service.Buy('aa');
  finally
    test.Free;
  end;
end;

end.