Simple Factory

  • 使用するクラスを切り替える場合、Factry Method 内で new している1ヶ所だけ修正すればよい。
  • クライアントの要求に応じて異なるオブジェクトを返せる。

  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // abstract product class
  5. class Product {
  6. public:
  7. virtual void Operation() = 0;
  8. };
  9.  
  10. // concrete product class
  11. class ProductA : public Product {
  12. public:
  13. void Operation() {
  14. cout << "ProductA Operation" << endl;
  15. }
  16. };
  17.  
  18. // concrete product class
  19. class ProductB : public Product {
  20. public:
  21. void Operation() {
  22. cout << "ProductB Operation" << endl;
  23. }
  24. };
  25.  
  26. // factory class
  27. class Factory {
  28. public:
  29. Product* CreateProduct(int id) {
  30. if (id == 0) {
  31. return new ProductA();
  32. } else {
  33. return new ProductB();
  34. }
  35. }
  36. };
  37.  
  38. // client
  39. int main(int argc, char **argv) {
  40. Factory *factory = new Factory();
  41. Product *product;
  42. for (int id=0; id<2; ++id) {
  43. product = factory->CreateProduct(id);
  44. product->Operation();
  45. delete product; // ほかの方法で。。
  46. }
  47. delete factory;
  48. return 0;
  49. }
  50.  

出力
ProductA Operation
ProductB Operation
最終更新:2012年01月31日 01:35