Refactoring Singleton Overuse

后端 未结 7 1979
一个人的身影
一个人的身影 2020-12-14 00:06

Today I had an epiphany, and it was that I was doing everything wrong. Some history: I inherited a C# application, which was really just a collection of static methods, a co

7条回答
  •  萌比男神i
    2020-12-14 01:00

    I recently had to tackle a similar problem, and what I did seemed to work well for me, maybe it will help you:

    (1) Group all "global" information into a single class. Let's call it Configuration.

    (2) For all classes which used to use these static objects, change them to (ultimately) inherit from a new abstract base class which looks something like

    abstract class MyBaseClass {
        protected Configuration config; // You can also wrap it in a property
        public MyBaseClass(Configuration config) {
            this.config = config;
        }
    }
    

    (3) Change all constructors of classes deriving from MyBaseClass accordingly. Then just create one instance of Configuration at start and pass it on everywhere.

    Cons:

    • You need to refactor many of your constructors and every place in which they are called
    • This won't work well if you do not derive your top-level classes from Object. Well, you can add the config field to the derived class, it's just less elegant.

    Pros

    • Not a lot of effort to just change inheritance and constructors, and bang - you can switch all Configuration.Instance with config.
    • You get rid of static variables completely; so no problems now if, for example, your application suddenly turns into a library and someone is trying to invoke multiple methods concurrently or whatever.

提交回复
热议问题