Best way to create a class collection

I am trying to create several classes that allow me to retrieve and manipulate the set of backups that my application will create and manage.

I came up with the following code (not tested yet), but I'm not sure if this is the best way to accomplish this or if there is an easier / better way. I am using Delphi 2010.

I have a class containing backup data (TBackupItem), then I need to have a class that will contain the TBackupItem collection, and finally I will have a class that controls reading and writing backups, and also provides a property that accesses TBackupItem collections.

type TBackupItem = class private FBackupProgram: string; FBackupProgramVersion: string; // There are more variables and properties but for the sake of simplicity I've listed only two public property BackupProgram: string read FBackupProgram write FBackupProgram; property BackupProgramVersion: string read FBackupProgramVersion write FBackupProgramVersion; end; TBackupsList = class(???) private // This class will hold a list of TBackupItem. What should I use to accomplish this? end; TBackupsManager = class(TObject) private FBackups: TBackupsList; public property Backups: TBackupsList read FBackups write FBackups; end; 

Do you have any comments and / or examples of the best way to accomplish this?

Thanks!

+4
source share
1 answer

In Delphi 2010, using Generics is the best approach.

Use this instead of your custom TBackupsList class:

 TBackupsManager = class private FBackups: TObjectList<TBackupItem>; 

(You must include Generics.Collections ).

If your collection needs additional methods, you can save TBackupsList and inherit it from TObjectList<TBackupItem> :

 TBackupsList = class(TObjectList<TBackupItem>) public function MyAdditionalMethod: Integer; end; 

EDIT: If you want to use custom TBackupsList but don’t want to have all the public TBackupsList methods available, you cannot use inheritance. Instead, you should use composition:

 TBackupsList = class private FItems: TObjectList<TBackupItem> public //Duplicates of the original TObjectList public methods accessing FItems. end; 
+12
source

Source: https://habr.com/ru/post/1307287/


All Articles