Last active
June 18, 2021 14:47
-
-
Save masaki-shimura/3f0b72b4a0597a6050fbade86166d315 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
/* | |
抽象ファクトリ のサンプルプログラム | |
説明 | |
複数のオブジェクトを一つのクラスで生成するデザイン | |
ポイント | |
・パーツ、工場ごとに抽象クラスがある | |
・生成用の静的メソッドでインスタンスを作る | |
*/ | |
#include <iostream> | |
using namespace std; | |
// 抽象クラス | |
class IRightHand | |
{ | |
public: | |
virtual void setup() = 0; | |
}; | |
class ILeftHand | |
{ | |
public: | |
virtual void setup() = 0; | |
}; | |
// 具象クラス | |
class PlayerLeftHand : public ILeftHand | |
{ | |
public: | |
void setup() | |
{ | |
cout <<"左手に牛乳を持つ\n"; | |
} | |
}; | |
class PlayerRightHand : public IRightHand | |
{ | |
public: | |
void setup() | |
{ | |
cout <<"右手にコーラを持つ\n"; | |
} | |
}; | |
class IHumanFactory | |
{ | |
public: | |
virtual IRightHand* createRightHand() = 0; | |
virtual ILeftHand* createLeftHand() = 0; | |
}; | |
class PlayerFactory : public IHumanFactory | |
{ | |
public: | |
IRightHand* createRightHand() | |
{ | |
return new PlayerRightHand(); | |
} | |
ILeftHand* createLeftHand() | |
{ | |
return new PlayerLeftHand(); | |
} | |
}; | |
// client | |
static void createHumanFactory(IHumanFactory* _factory) | |
{ | |
cout << "工場で登録されているレシピからオブジェクトを順次生成する\n"; | |
ILeftHand* __leftHand = _factory->createLeftHand(); | |
IRightHand* __rightHand = _factory->createRightHand(); | |
__leftHand->setup(); | |
__rightHand->setup(); | |
} | |
int main(void) | |
{ | |
createHumanFactory(new PlayerFactory()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment