Commandパターン

「コマンド=命令」

という事で、命令をクラスとして扱うためのパターンです。

コマンドクラス生成をして、そのクラスが司るコマンド(命令)を実行する。

ただそれだけのことです。

書いてみよかー


// コマンド基底クラス
class CommandBase
{
public:
CommandBase(){}
~CommandBase(){}
public:
virtual void CallCommand(){}
};

// ○○拳
class RisingDragonUpper : public CommandBase
{
public:
RisingDragonUpper(){}
~RisingDragonUpper(){}
public:
virtual void CallCommand()
{
printf("○○拳!");
}
};

// ○○フレ○○
class GunFrame : public CommandBase
{
public:
GunFrame(){}
~GunFrame(){}
public:
virtual void CallCommand()
{
printf("○○フレ○○!");
}
};

// ○○○スパイ○
class DeadSpike : public CommandBase
{
public:
DeadSpike(){}
~DeadSpike(){}
public:
virtual void CallCommand()
{
printf("○○○ス○○ク!");
}
};

// プレイヤーキャラクター(がいるとする)
class PlayerCharacter
{
enum
{
SKILL_RISINGDRAGONUPPER,
SKILL_GUNFRAME,
SKILL_DEADSPIKE,
};
public:
PlayerCharacter(){}
~PlayerCharacter(){}
public:
bool DoSkill(int id)
{
CommandBase* pCom = NULL;

// コマンド生成
switch(id)
{
case SKILL_RISINGDRAGONUPPER:
pCom = new RisingDragonUpper();
break;
case SKILL_GUNFRAME:
pCom = new GunFrame();
break;
case SKILL_DEADSPIKE:
pCom = new DeadSpike();
break;
}

// ミス
if (pCom == NULL) return false;

// コマンド発行
pCom->CallCommand();

// コマンド削除
delete pCom;

// コマンドでたのぉ?ねぇ
return true;

};
};

int main()
{
// キャラク
PlayerCharacter Player;

// 技だす
Player.DoSkill(Player::SKILL_GUNFRAME);

return 0;
}


「格ゲーやりたいやりたい」と考えながら書いたらこうなった。


コマンドパターンは命令の追加も楽だしメンテも比較的し易いので
よく使われてるのを見ます。

こんなに雑じゃないけどね!