Object orientation and serialization

这一生的挚爱 提交于 2019-12-05 14:06:12

One solution would be to implement a factory where all classes register themselve with a unique ID.

TCustomClassFactory = class(TObject)
public      
  procedure Register(AClass: TClass; ID: Integer);
  function Create(const ID: Integer): IMyInterface;
end;

TProductionClassFactory = class(TCustomClassFactory)
public
  constructor Create; override;
end;

TTestcase1ClassFactory = class(TCustomClassFactory);
public
  constructor Create; override;
end;

var
  //***** Set to TProductionClassFactory for you production code,
  //      TTestcaseXFactory for testcases or pass a factory to your loader object.
  GlobalClassFactory: TCustomClassFactory;

implementation

constructor TProductionClassFactory.Create;
begin
  inherited Create;
  Register(TMyImplementingClass1, 1);
  Register(TMyImplementingClass2, 2);
end;

constructor TTestcase1ClassFactory.Create;
begin
  inherited Create;
  Register(TMyImplementingClass1, 1);
  Register(TDoesNotImplementIMyInterface, 2);
  Register(TDuplicateID, 1);
  Register(TGap, 4);
  ...
end;

Advantages

  • You can remove the conditional logic from your current load method.
  • One place to check for duplicate or missing ID's.

You need a class registry, where you store every class reference together with their unique ID. The classes register themselves in the initialization section of their unit.

TImplementingClass1 = class (TInterfacedObject, IMyInterface)
  ...
end;
TImplementingClass2 = class (TInterfacedObject, IMyInterface)
  ...
end;

TMainClass = class
public
  procedure LoadFromFile (const FileName : String);
  procedure SaveToFile (const FileName : String);
end;

Edit: moved the class registry into a separate class:

TMyInterfaceContainer = class 
strict private
class var
  FItems : TList <IMyInterface>;
  FIDs: TList<Integer>;
public
  class procedure RegisterClass(TClass, Integer);
  class function GetMyInterface(ID: Integer): IMyInterface;
end;

procedure TMainClass.LoadFromFile (const FileName : String);
  ...
  ID := Reader.ReadInteger;
  // case ID of
  //   itClass1 : Item := TImplementingClass1.Create;
  //   itClass2 : Item := TImplementingClass2.Create;
  //   ...
  // end;
  Item := TMyInterfaceContainer.GetMyInterface(ID);
  Item.Load (Stream);
  ...

initialization
  TMyInterfaceContainer.RegisterClass(TImplementingClass1, itClass1);
  TMyInterfaceContainer.RegisterClass(TImplementingClass2, itClass2);

This should point you into the direction, for a very good introduction into these methods read the famous Martin Fowler article, esp. the section about Interface Injection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!