Can an observable class be constructed as a singleton?

前端 未结 3 1791
悲&欢浪女
悲&欢浪女 2021-01-28 17:13

I\'m making a program in Java with the Observer pattern (with the help of the Java API). If some of the observables had more than one instance, the program could crash. Should I

相关标签:
3条回答
  • 2021-01-28 17:44

    Should I implement them as singleton? Is it recommended?

    Of course you can do this. Whether it is a good idea depends on the actual context.

    • Are these things conceptually singleton, or is this just a hack to try to make bugs disappear? (Or to put it another way, is the real problem that your application design is wrong ...)

    • Singletons do have issues with respect to unit testing. This is not a show stopper, but it is one of the reasons that people tend to avoid them.

    0 讨论(0)
  • 2021-01-28 17:45

    Yes, the GoF lists the Singleton as a related pattern (along with the Mediator) to the Observer:

    The ChangeManager may use the Singleton pattern to make it unique and globally accessible.

    ChangeManager is their Observable in the sample code.

    I have used a Singleton Observable (here) to update the GUI everytime relevant changes occur to the Persistence Unit. The program won't crash but it won't function as expected if there were more instances.

    0 讨论(0)
  • 2021-01-28 17:49

    I did it before and didn't have any problems exactly because I used a singleton. The pattern is there to use it.

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