code_junkie

How should I refactor my code to remove unnecessary singletons

Nov 13th, 2011
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. Store managedStore = Store::getInstance();
  2. managedStore.doSomething();
  3. managedStore.doSomethingElse();
  4. //etc.
  5.  
  6. someVar = SomeControllerClass(managedStore, menuBar, editor, sasquatch, ...)
  7.  
  8. var parameterClass1 = new MenuParameter(menuBar, editor);
  9. var parameterClass2 = new StuffParameters(sasquatch, ...);
  10.  
  11. var ctrl = new MyControllerClass(managedStore, parameterClass1, parameterClass2);
  12.  
  13. // The Rather Unfortunate Singleton Class
  14. public class SingletonStore {
  15. private static SingletonStore _singleton
  16. = new MyUnfortunateSingleton();
  17.  
  18. private SingletonStore() {
  19. // Do some privatised constructing in here...
  20. }
  21.  
  22. public static SingletonStore getInstance() {
  23. return _singleton;
  24. }
  25.  
  26. // Some methods and stuff to be down here
  27. }
  28.  
  29. // Usage:
  30. // var singleInstanceOfStore = SingletonStore.getInstance();
  31.  
  32. public class StoreWithFactory {
  33.  
  34. public StoreWithFactory() {
  35. // If the constructor is private or public doesn't matter
  36. // unless you do TDD, in which you need to have a public
  37. // constructor to create the object so you can test it.
  38. }
  39.  
  40. // The method returning an instance of Singleton is now a
  41. // factory method.
  42. public static StoreWithFactory getInstance() {
  43. return new StoreWithFactory();
  44. }
  45. }
  46.  
  47. // Usage:
  48. // var myStore = StoreWithFactory.getInstance();
  49.  
  50. class Log
  51. {
  52. void logmessage(...)
  53. { // do some stuff
  54. }
  55. };
  56.  
  57. int main()
  58. {
  59. Log log;
  60.  
  61. // do some more stuff
  62. }
  63.  
  64. class Database
  65. {
  66. Log &_log;
  67. Database(Log &log) : _log(log) {}
  68. void Open(...)
  69. {
  70. _log.logmessage(whatever);
  71. }
  72. };
Add Comment
Please, Sign In to add comment