Delphi类和方法。需要一个方法实现多个类

时间:2019-03-05 23:48:21

标签: class oop delphi

例如,我有一个农场的蔬菜课。

TVegetable = class

TCarrot = class(TVegetable)
TTomato = class(TVegetable)

每种蔬菜我需要两种不同的类别,一种用于超市,另一种用于工厂。

TCarrotSupermarket = class(TCarrot)
TCarrotFactory = class(TCarrot)

除了一种方法的代码外,这些类是相同的:

procedure Utilization;

TCarrotSupermarket.Utilization适用于超市,TCarrotFactory.Utilization适用于工厂。

我需要为Utilization使用一个相同的代码 TCarrotSupermarket.UtilizationTTomatoSupermarket.UtilizationTPotatoSupermarket.Utilization和另一个代码 TCarrotFactory.UtilizationTTomatoFactory.UtilizationTPotatoFactory.Utilization

为超市Utilization仅编写两次代码(对于超市和工厂)并在适当的类中使用它的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

欢迎使用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);

答案 1 :(得分:0)

以下是使用接口方法解析解决方案的一些伪代码。 (未经测试,甚至没有编译,但是应该可以为您指明正确的方向)

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;

或者使用支持例程

VAR lFactory:IFactoryInterface;
...
if supports(lSomeVegetable,IFactoryInterface,lFactory) then
  lFactory.Utilization
...

希望这会对您有所帮助。这是一些匹配的documentation

的指针
相关问题