ConsoleApplication2.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <iostream>
  2. #include <string>
  3. #include <stdlib.h>
  4. using namespace std;
  5. class Number
  6. {
  7. public:
  8. // 2. Define a public static accessor func
  9. static Number* instance();
  10. static void setType(string t)
  11. {
  12. type = t;
  13. delete inst;
  14. inst = 0;
  15. }
  16. virtual void setValue(int in)
  17. {
  18. value = in;
  19. }
  20. virtual int getValue()
  21. {
  22. return value;
  23. }
  24. protected:
  25. int value;
  26. // 4. Define all ctors to be protected
  27. Number()
  28. {
  29. cout << ":ctor: ";
  30. }
  31. // 1. Define a private static attribute
  32. private:
  33. static string type;
  34. static Number* inst;
  35. };
  36. class Octal : public Number
  37. {
  38. // 6. Inheritance can be supported
  39. public:
  40. friend class Number;
  41. void setValue(int in)
  42. {
  43. char buf[10];
  44. sprintf_s(buf, "%o", in);
  45. sscanf_s(buf, "%d", &value);
  46. }
  47. protected:
  48. Octal() {}
  49. };
  50. Number* Number::instance()
  51. {
  52. if (!inst)
  53. // 3. Do "lazy initialization" in the accessor function
  54. if (type == "octal")
  55. inst = new Octal();
  56. else
  57. inst = new Number();
  58. return inst;
  59. }
  60. string Number::type = "decimal";
  61. Number* Number::inst = 0;
  62. int main()
  63. {
  64. // Number myInstance; - error: cannot access protected constructor
  65. // 5. Clients may only use the accessor function to manipulate the Singleton
  66. Number::setType("octal");
  67. Number::instance()->setValue(42);
  68. cout << "value is " << Number::instance()->getValue() << endl;
  69. Number::setType("decimal");
  70. Number::instance()->setValue(64);
  71. cout << "value is " << Number::instance()->getValue() << endl;
  72. Number::setType("decimal");
  73. Number::instance()->setValue(42);
  74. cout << "value is " << Number::instance()->getValue() << endl;
  75. Number::setType("octal");
  76. Number::instance()->setValue(64);
  77. cout << "value is " << Number::instance()->getValue() << endl;
  78. }