インタフェース委任の実装--クラスのオブジェクトを介して

1826 ワード

unit Interfacce; { -- }

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;

  IMyInterface = interface
    function Sell(const s: string): Boolean;
    function Buy(const s: string): Boolean;
  end;

  TMyClass = class(TInterfacedObject, IMyInterface)
  protected
    function Sell(const s: string): Boolean;
    function Buy(const s: string): Boolean;
  end;

  TMyClass2 = class(TInterfacedObject, IMyInterface)
  private
//    FmyClass: TMyClass;
    function GetMyClass: TMyClass;  { }
  public
    property myService: TMyClass read GetMyClass implements IMyInterface;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  myClass2: TMyClass2;
begin
  try
    myClass2 := TMyClass2.Create;
    myClass2.myService.Sell('Book');
    myClass2.myService.Buy('Book')
  finally
    myClass2.Free;
  end;
end;

{ TMyClass }

function TMyClass.Buy(const s: string): Boolean;
begin
  ShowMessage('Buy ' + s);
end;

function TMyClass.Sell(const s: string): Boolean;
begin
  ShowMessage('Sell ' + s);
end;

{ TMyClass2 }

function TMyClass2.GetMyClass: TMyClass;
begin
//
end;

end.