Skip to content

Instantly share code, notes, and snippets.

@masaki-shimura
Created June 18, 2021 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masaki-shimura/25b1c136a488b81ed79f97904b0c4ff9 to your computer and use it in GitHub Desktop.
Save masaki-shimura/25b1c136a488b81ed79f97904b0c4ff9 to your computer and use it in GitHub Desktop.
【デザインパターン】コンポジット
/*
複合パターン のサンプルプログラム
説明
入れ子のようにオブジェクトを格納することが出来るパターン
ポイント
・ひとつの抽象クラスをベースにすべてのクラスが継承する
・その一つがデータを保持するデザイン
*/
#include <iostream>
#include <list>
using namespace std;
class Bullet
{
public:
virtual void draw() = 0;
};
class RedBullet : public Bullet
{
public:
void draw() override
{
cout << "red bullet \n";
}
};
class BlueBullet : public Bullet
{
public:
void draw() override
{
cout << "blue bullet\n";
}
};
class Magazine : public Bullet
{
public:
void add(Bullet* _bullet)
{
m_listBullet.push_back(_bullet);
}
void remove(Bullet* _bullet)
{
m_listBullet.remove(_bullet);
}
void draw() override
{
if(m_listBullet.size() <= 0)
{
cout << "弾丸がマガジンに入っていません\n";
return;
}
cout << "マガジンの中を確認します。\n";
for(Bullet* __pBullet : m_listBullet)
{
__pBullet->draw();
}
}
private:
list<Bullet*> m_listBullet = {};
};
int main(void){
// Your code here!
Magazine _magazine;
_magazine.add(new RedBullet);
_magazine.add(new BlueBullet);
Magazine _magazineBag;
_magazineBag.add(&_magazine);
//_magazineBag.add(new Magazine);
_magazineBag.draw();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment