Design Patterns - Factory Method - Example 1


// factory_method_example.cpp, 2012-06-05 T2146
// @history  
// 2012-06-05  init 

#include <iostream>
#include <string>

using namespace std;

// interface Product
class Product {
  public:
    virtual string getName() = 0;
};

// interface ProductOperator
class ProductOperator {
  public:
    virtual void operation() {
      Product *product = createProduct();
      cout << "Product " << product->getName() << " is beeing done something, after created." << endl;
      delete product;
      product = NULL;
    }

    virtual Product *createProduct() = 0;  //<! This is Factory Method!!!!
};

// class A_Product implements Product
// for factory A_ProductOperator
class A_Product : public Product {
  public:
    string getName() {
      return "A_Product";
    }
};

// class B_Product implements Product
// for factory B_ProductOperator
class B_Product : public Product {
  public:
    string getName() {
      return "B_Product";
    }
};

// class A_ProductOperator implements ProductOperator
// create product A_Product
class A_ProductOperator : public ProductOperator {
  Product *createProduct() {
    return new A_Product();
  }
};

// class B_ProductOperator implements ProductOperator
// create product B_Product
class B_ProductOperator : public ProductOperator {
  Product *createProduct() {
    return new B_Product();
  }
};


int main(int argc, char *argv[])
{
  ProductOperator * aFactory = new A_ProductOperator();
  ProductOperator * bFactory = new B_ProductOperator();

  aFactory->operation();
  bFactory->operation();

  // cout << "Press the enter key to continue ...";
  // cin.get();
  return 0;
}