What is the best way to serialize Delphi application configuration?

后端 未结 7 1738
猫巷女王i
猫巷女王i 2021-02-02 02:21

I will answer this question myself, but feel free to provide your answers if you are faster than me or if you don\'t like my solution. I just came up with this idea and would li

7条回答
  •  说谎
    说谎 (楼主)
    2021-02-02 03:00

    My preferred method is to create an interface in my global interfaces unit:

    type
      IConfiguration = interface
        ['{95F70366-19D4-4B45-AEB9-8E1B74697AEA}']
        procedure SetConfigValue(const Section, Name,Value:String);
        function GetConfigValue(const Section, Name:string):string;
      end;
    

    This interface is then "exposed" in my main form:

    type
      tMainForm = class(TForm,IConfiguration)
      ...
      end;
    

    Most of the time the actual implementation is not in the main form, its just a place holder and I use the implements keyword to redirect the interface to another object owned by the main form. The point of this is that the responsibility of configuration is delegated. Each unit doesn't care if the configuration is stored in a table, ini file, xml file, or even (gasp) the registry. What this DOES allow me to do in ANY unit which uses the global interfaces unit is make a call like the following:

    var
      Config : IConfiguration;
      Value : string;
    begin
      if Supports(Application.MainForm,IConfiguration,Config) then
        value := Config.GetConfiguration('section','name');
      ...      
    end;
    

    All that is needed is adding FORMS and my global interfaces unit to the unit I'm working on. And because it doesn't USE the mainform, if I decide to later reuse this for another project, I don't have to do any further changes....it just works, even if the configuration storage scheme is completely different.

    My general preference is to create a table (if I'm dealing with a database application) or an XML file. If it is a multi-user database application, then I will create two tables. One for global configuration, and another for user configuration.

提交回复
热议问题