介紹
將同性質的類的個體差異另外拉出來定義一個類,不同實作的此類讓引入它的原類表示出不同的類型。
以下範例取自Game Programming Pattern一書:
多個怪物子類的行為透過繼承並覆寫Monster基類來達成。但若怪物子類很多時,一個個覆寫會很麻煩,且造成繼承階層肥大,這時將這些覆寫部分拉出去各自實作再引入回去。
原本要一個個覆寫怪物的行為:
class Monster
{
public:
virtual ~Monster() {}
virtual const char* getAttack() = 0;
protected:
Monster(int startingHealth)
: health_(startingHealth)
{}
private:
int health_; // Current health.
};
class Dragon : public Monster
{
public:
Dragon() : Monster(230) {}
virtual const char* getAttack()
{
return "The dragon breathes fire!";
}
};
class Troll : public Monster
{
public:
Troll() : Monster(48) {}
virtual const char* getAttack()
{
return "The troll clubs you!";
}
};
將這些覆寫部分拉出去各自實作(範例為Breed類),再引入回去:
class Breed
{
public:
Breed(int health, const char* attack)
: health_(health),
attack_(attack)
{}
int getHealth() { return health_; }
const char* getAttack() { return attack_; }
private:
int health_; // Starting health.
const char* attack_;
};
class Monster
{
public:
Monster(Breed& breed)
: health_(breed.getHealth()),
breed_(breed)
{}
const char* getAttack()
{
return breed_.getAttack();
}
private:
int health_; // Current health.
Breed& breed_;
};
Ref:
https://gameprogrammingpatterns.com/type-object.html