delphi – 面向对象和序列化
发布时间:2020-12-15 09:23:46 所属栏目:大数据 来源:网络整理
导读:考虑像这样的界面 IMyInterface = interface procedure DoSomethingRelevant; procedure Load (Stream : TStream); procedure Save (Stream : TStream);end; 以及几个实现该接口的类: TImplementingClass1 = class (TInterfacedObject,IMyInterface) ...end
考虑像这样的界面
IMyInterface = interface procedure DoSomethingRelevant; procedure Load (Stream : TStream); procedure Save (Stream : TStream); end; 以及几个实现该接口的类: TImplementingClass1 = class (TInterfacedObject,IMyInterface) ... end; TImplementingClass2 = class (TInterfacedObject,IMyInterface) ... end; ... 我有一个包含IMyInterface实现者列表的类: TMainClass = class strict private FItems : TList <IMyInterface>; public procedure LoadFromFile (const FileName : String); procedure SaveToFile (const FileName : String); end; 现在问题是:如何以面向对象的方式加载主类,尤其是项目列表?在我可以为项目调用虚拟Load方法之前,我必须创建它们,因此必须知道它们的类型.在我当前的实现中,我存储项目数,然后存储每个项目 >类型标识符(IMyInterface获取额外的GetID函数) 但这意味着在加载过程中我必须做类似的事情 ID := Reader.ReadInteger; case ID of itClass1 : Item := TImplementingClass1.Create; itClass2 : Item := TImplementingClass2.Create; ... end; Item.Load (Stream); 但这似乎并不是面向对象的,因为每次添加新的实现者时我都必须使用现有的代码.有没有更好的方法来处理这种情况? 解决方法
一种解决方案是实现一个工厂,其中所有类都使用唯一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; 好处 >您可以从当前的加载方法中删除条件逻辑.>一个地方检查重复或丢失的ID. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |