ok , global variable is condemned, singleton is despised, what's the alternative?

前端 未结 9 2391
终归单人心
终归单人心 2020-12-08 09:58

For desktop application that is. This is just a general question that maybe only need general answers.

相关标签:
9条回答
  • 2020-12-08 10:16

    A static class with static data members? But who cares. Static data members are just global variables with more politically correct packaging.

    Don't let fashion override your common sense. There's nothing wrong with using a plain old global variable. The singleton pattern is often overkill and annoying to type, and annoying when you are single stepping through code to debug it.

    Assuming you are using C/C++, I would recommend that you not have global variables that are class instances that allocate memory from the heap. They will make it harder for you to use tools that check for memory leaks. Declare the global as a pointer, new it at the beginning of main(), delete it at the end.

    EDIT AFTER 6 COMMENTS: Think of logging. Wouldn't you want to be able to write a line to your log from anywhere in your app? How concretely do you accomplish that without there being something globally visible to do that logging? If you want something globally visible, then go ahead and make it globally visible.

    0 讨论(0)
  • 2020-12-08 10:16

    after using globals and singletons and seeing everything get messed, I came up to this solution.

    1. make every global variable a member of a class. Logically every global variable belongs to application (or system). just create an application class. define global objects as properties. so they are created when first called.

    2. create a singleton for application class, so you can access it globally. This will be the only singleton in your code. well, at the end it is like system.out or system.in objects in java.

    note: I know that, this is a very old question, but still popular.

    0 讨论(0)
  • 2020-12-08 10:26

    I wouldn't care if singleton or global variables are not recommended. If I feel like that is the most logical way of implementing it then I'll go ahead and use it.

    0 讨论(0)
提交回复
热议问题