举个例子,我给一个农场安排了蔬菜班。
TVegetable = class
TCarrot = class(TVegetable)
TTomato = class(TVegetable)我需要两种不同种类的蔬菜,一种用于超市,另一种用于工厂。
TCarrotSupermarket = class(TCarrot)
TCarrotFactory = class(TCarrot)除了一个方法的代码之外,这些类都是相同的:
procedure Utilization;TCarrotSupermarket.Utilization与超市合作,TCarrotFactory.Utilization与工厂合作。
我需要一个相同的Utilization代码用于TCarrotSupermarket.Utilization、TTomatoSupermarket.Utilization、TPotatoSupermarket.Utilization,另一个代码用于TCarrotFactory.Utilization、TTomatoFactory.Utilization、TPotatoFactory.Utilization。
只为Utilization编写两次代码(对于超市和工厂)并在适当的类中使用它的最佳方式是什么?
发布于 2019-03-07 03:00:30
欢迎使用Pattern Design。你的案例是Strategy patternn
class TStrategyVegetable = class(TVegetable)
FUtil: TUtilization
public
procedure Create(util: TUtilization);
procedure Utilization();
end
procedure TStrategyVegetable.Create(util: TUtilization)
begin
FUtil := util
end
procedure TStrategyVegetable.Utilization;
begin
FUtil.Utilization;
end然后在代码中:
carrotSupermarket = TCarrotSupermarket.Create(TCarrotSupermarketUtil.Create);
carrotFactory = TCarrotFactory.Create(TCarrotFactoryUtil.Create);发布于 2019-03-07 16:37:45
下面是使用接口方法解析解决方案的一些伪代码。(未经测试,甚至没有编译,但它应该会为您指明正确的方向)
IFactoryInterface=interface(IUnknown) ['{someGUID}']
procedure Utilization;
end;
ISuperMarketInterface=interface(IUnknown) ['{AnotherGUID}']
procedure Utilization;
end;
TVegetable = class (TSomeObject,IFactoryInterface,ISupermarketInterface)
protected
// the routines tha do the actual implementation
// can be regular virtual, dynamic, or whatever
procedure FactoryUtilization;
procedure SuperMarketUtilization;
// link up the interfaces using method resolution
procedure IFactoryInterface.Utilization=FactoryUtilization;
procedure ISupermarketInterface.Utilization=SuperMarketUtilization;
{ in case not derived from TInterfacedObject,
You'll have to add _AddRef,_Release and
QueryInterface methods too }
end;
// the other implementations can be as before
TCarrot = class(TVegetable)
TTomato = class(TVegetable)然后,当使用代码时,它应该看起来像这样:
VAR lSOmeVegetable,lAnotherVegetable:TVegetable;
...
lSomeVegetable:=TCarrot.Create
lanotherVegetable:=Tomato.Create
...
// call using buolt-in type checking
(lSOmeVegetable as IFactoryInterface).Utilization;
(lAnotherVegetable as ISuperMarketInterface).Utilization;或以其他方式使用support例程
VAR lFactory:IFactoryInterface;
...
if supports(lSomeVegetable,IFactoryInterface,lFactory) then
lFactory.Utilization
...希望这能对你有所帮助。这里有一个指向一些匹配的documentation的指针
https://stackoverflow.com/questions/55013388
复制相似问题