Singleton for Application Configuration

前端 未结 6 491
南方客
南方客 2021-02-05 02:49

In all my projects till now, I use to use singleton pattern to access Application configuration throughout the application. Lately I see lot of articles taking about not to use

6条回答
  •  说谎
    说谎 (楼主)
    2021-02-05 03:12

    I think an application configuration is an excellent use of the Singleton pattern. I tend to use it myself to prevent having to reread the configuration each time I want to access it and because I like to have the configuration be strongly typed (i.e, not have to convert non-string values each time). I usually build in some backdoor methods to my Singleton to support testability -- i.e., the ability to inject an XML configuration so I can set it in my test and the ability to destroy the Singleton so that it gets recreated when needed. Typically these are private methods that I access via reflection so that they are hidden from the public interface.

    EDIT We live and learn. While I think application configuration is one of the few places to use a Singleton, I don't do this any more. Typically, now, I will create an interface and a standard class implementation using static, Lazy backing fields for the configuration properties. This allows me to have the "initialize once" behavior for each property with a better design for testability.

提交回复
热议问题