- 使用するクラスを切り替える場合、Factry Method 内で new している1ヶ所だけ修正すればよい。
- クライアントの要求に応じて異なるオブジェクトを返せる。
#include <iostream>
using namespace std;
// abstract product class
class Product {
public:
virtual void Operation() = 0;
};
// concrete product class
class ProductA : public Product {
public:
void Operation() {
cout << "ProductA Operation" << endl;
}
};
// concrete product class
class ProductB : public Product {
public:
void Operation() {
cout << "ProductB Operation" << endl;
}
};
// factory class
class Factory {
public:
Product* CreateProduct(int id) {
if (id == 0) {
return new ProductA();
} else {
return new ProductB();
}
}
};
// client
int main(int argc, char **argv) {
Factory *factory = new Factory();
Product *product;
for (int id=0; id<2; ++id) {
product = factory->CreateProduct(id);
product->Operation();
delete product; // ほかの方法で。。
}
delete factory;
return 0;
}
出力
ProductA Operation
ProductB Operation
最終更新:2012年01月31日 01:35