Is a “master preferences” class a good idea?

前端 未结 6 1582
走了就别回头了
走了就别回头了 2021-02-06 06:50

I have a class that manages user preferences for a large software project. Any class in the project that may need to set or retrieve a user preference from a persistent store i

6条回答
  •  盖世英雄少女心
    2021-02-06 07:14

    You might want to look at Cocoa's NSUserDefaults class for inspiration. It handles the problem you describe by having several layers of preferences, called domains. When you look up the value for a key, such as "PrintUsingAllCaps", it first checks for a value in the user's local domain. If it isn't found there, it can check the system-wide domain, or a network-level domain, and so on.

    The absolute last place it checks is called the "Registration Domain", which is basically where hard coded defaults are supposed to go. So, at any point in my code, I can write a preference into the registration domain, and NSUserDefaults will only serve that value if the user hasn't overridden it.

    So, in your case, you could provide a method for classes to set a default value for a key before it accesses the (possibly) user defined value. The preferences class doesn't have to know anything about the classes it is serving.

    As somebody else suggested, if you need something more sophisticated, you could set a DefaultValueProvider callback object instead of a straight value.

提交回复
热议问题