- 多用合成 ,少用繼承 (More composition less inheritance)
- 使用合成建立系統具有很大的彈性,不僅可以將演算法封裝成類別,更可以在執行期動態改變行為,只要合成的行為物件,符合特定的介面標準即可。
#include <stdlib.h>
#include <stdio.h>
// particular interface
class IFlyBehavior
{
public:
virtual void fly(void) = 0;
};
// The interface implementance
class CFlyWithWings : public IFlyBehavior
{
public:
virtual void fly(void)
{
printf("I'm flying\n");
}
};
// The interface implementance
class CFlyNoWay : public IFlyBehavior
{
public:
virtual void fly(void)
{
printf("I can't fly\n");
}
};
// particular interface
class IQuackBehavior
{
public:
virtual void quack(void) = 0;
};
// The interface implementance
class CQuack : public IQuackBehavior
{
public:
virtual void quack(void)
{
printf("Quick\n");
}
};
// The interface implementance
class CMuteQuack : public IQuackBehavior
{
public:
virtual void quack(void)
{
printf("<<silence>>\n");
}
};
class Squeak : public IQuackBehavior
{
public:
virtual void quack(void)
{
printf("Squeak\n");
}
};
class CDuck
{
protected:
IFlyBehavior *m_flyBehavior; // more fixable
IQuackBehavior *m_quackBehavior; // more fixable
public:
CDuck(){}
virtual ~CDuck(){}
virtual void display() = 0;
virtual void performQuack(void)
{
m_quackBehavior->quack();
}
virtual void performFly(void)
{
m_flyBehavior->fly();
}
virtual void swim()
{
printf("All duck float, even decoys!");
}
};
class CMallardDuck : public CDuck
{
public:
CMallardDuck()
{
m_flyBehavior = new CFlyWithWings(); // can be replacement at runtime
m_quackBehavior = new CQuack();
}
virtual ~CMallardDuck()
{
delete m_flyBehavior;
delete m_quackBehavior;
}
virtual void display(void)
{
}
};
int main()
{
CDuck &mallard = *(new CMallardDuck());
mallard.performQuack();
mallard.performFly();
return 0;
}
沒有留言:
張貼留言