unit factory;
interface
uses windows, messages, sysutils, controls, product;
type
ifactoryinterface = interface
function factory(): iproductinterface;
end;
tfactory1 = class(tcontrol, ifactoryinterface)
public
function factory(): iproductinterface;
end;
tfactory2 = class(tcontrol, ifactoryinterface)
public
function factory(): iproductinterface;
end;
implementation
function tfactory1.factory(): iproductinterface;
var
aproduct: tproduct1;
begin
aproduct := tproduct1.create(nil);
result := aproduct.createproduct();
end;
function tfactory2.factory(): iproductinterface;
var
aproduct: tproduct2;
begin
aproduct := tproduct2.create(nil);
result := aproduct.createproduct();
end;
end.
unit product;
interface
uses windows, messages, sysutils, controls, dialogs;
type
iproductinterface = interface
function createproduct(): iproductinterface;
end;
tproduct1 = class(tcontrol, iproductinterface)
public
function createproduct(): iproductinterface;
end;
tproduct2 = class(tcontrol, iproductinterface)
public
function createproduct(): iproductinterface;
end;
implementation
function tproduct1.createproduct(): iproductinterface;
begin
result := self;
showmessage('product1 created');
end;
function tproduct2.createproduct(): iproductinterface;
begin
result := self;
showmessage('product2 created');
end;
end.
//测试
procedure tform1.button1click(sender: tobject);
var
afactory: tfactory1;
begin
afactory := tfactory1.create(self);
afactory.factory;
freeandnil(afactory);
end;
procedure tform1.button2click(sender: tobject);
var
afactory: tfactory2;
begin
afactory := tfactory2.create(self);
afactory.factory;
freeandnil(afactory);
end;