fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5. class BaseClass {
  6. public:
  7. BaseClass() { cout << "Constructor BaseClass" << endl; }
  8. virtual void Tell() { cout << "I'm BaseClass" << endl; }
  9. };
  10.  
  11. class ClassA: public BaseClass {
  12. public:
  13. ClassA() { cout << "Constructor ClassA" << endl; }
  14. void Tell() { cout << "I'm ClassA" << endl; }
  15. };
  16.  
  17. class ClassB: public BaseClass {
  18. public:
  19. ClassB() { cout << "Constructor ClassB" << endl; }
  20. void Tell() { cout << "I'm ClassB" << endl; }
  21. };
  22.  
  23.  
  24. class BaseFactory {
  25. public:
  26. BaseFactory() { cout << "BaseFactory constructor" << endl; }
  27. virtual void Tell() const { cout << "I'm BaseFactory" << endl; }
  28. virtual BaseClass * Produce() const { return new BaseClass(); }
  29. };
  30.  
  31. class FactoryA: public BaseFactory {
  32. public:
  33. FactoryA() { cout << "FactoryA constructor" << endl; }
  34. void Tell() const { cout << "I'm FactoryA" << endl; }
  35. BaseClass * Produce() const {
  36. cout << "FactoryA produce:" << endl;
  37. return new ClassA();
  38. }
  39. };
  40.  
  41. class FactoryB: public BaseFactory {
  42. public:
  43. FactoryB() { cout << "FactoryB constructor" << endl; }
  44. void Tell() const { cout << "I'm FactoryB" << endl; }
  45. BaseClass * Produce() const {
  46. cout << "FactoryA produce:" << endl;
  47. return new ClassB();
  48. }
  49. };
  50.  
  51.  
  52. static BaseFactory * factoryA = new FactoryA();
  53. static BaseFactory * factoryB = new FactoryB();
  54.  
  55.  
  56. void CreateSome( BaseClass* &object, const BaseFactory& SomeFactory ) {
  57. SomeFactory.Tell();
  58. object = SomeFactory.Produce();
  59. }
  60.  
  61. int main()
  62. {
  63. BaseClass* T;
  64. CreateSome(T, *factoryA);
  65. T->Tell();
  66. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
BaseFactory constructor
FactoryA constructor
BaseFactory constructor
FactoryB constructor
I'm FactoryA
FactoryA produce:
Constructor BaseClass
Constructor ClassA
I'm ClassA