-
-
Save masaki-shimura/0b25bf01f093d3d2ac8f7f8bb8d7db92 to your computer and use it in GitHub Desktop.
【デザインパターン】ファクトリメソッド
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
ファクトリメソッド のサンプルプログラム | |
説明 | |
・生成する処理を切り離す事により、生成処理の差し替えを柔軟にする事が出来るデザインパターン | |
ポイント | |
・実態クラス と 生成クラスで 一組 | |
・その一組で 具象クラスと抽象クラスで分かれているイメージ | |
下記サイトより引用 | |
このパターンは「Virtual Constructor」とも呼ばれ、コンストラクタの代わりになるようなメソッドを作ることがキモなパターンです。 | |
コンストラクタの代わりにインスタンスの工場(Factory)となるメソッド(Method)を作るから「FactoryMethod」パターンなんですね。 | |
★具象クラスの代わりにインタフェースや抽象クラスを使ってインスタンス生成する | |
// 要確認 | |
https://blog.ecbeing.tech/entry/2021/01/20/114000 | |
*/ | |
#include <iostream> | |
using namespace std; | |
/////////////////////////////////// | |
// 抽象クラス | |
/////////////////////////////////// | |
// Product (製品) | |
class Car | |
{ | |
public: | |
virtual void printName() | |
{ | |
cout << "\n車"; | |
} | |
}; | |
// Creator | |
// インスタンス生成用のクラス | |
class CarCreator | |
{ | |
public: | |
void printName() | |
{ | |
createCar()->printName(); | |
} | |
private: | |
virtual Car* createCar() | |
{ | |
cout << "\nCar が生成された。"; | |
return new Car(); | |
} | |
}; | |
/////////////////////////////////// | |
// 具象クラス | |
/////////////////////////////////// | |
// Concrete Product (具体的な製品) | |
// プリウス | |
class Prius : public Car | |
{ | |
private: | |
void printName() | |
{ | |
cout << "\nプリウス"; | |
}; | |
}; | |
//ConcreteCreator (具体的な生成) | |
class PriusCreator : public CarCreator | |
{ | |
private: | |
//★ ファクトリーメソッド | |
Car* createCar() | |
{ | |
cout << "\nPrius が生成された。"; | |
return new Prius(); | |
} | |
}; | |
int main(void){ | |
// 基底クラスで生成 | |
CarCreator _carCreator; | |
_carCreator.printName(); | |
//下記 | |
PriusCreator _priusCreator; | |
_priusCreator.printName(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment