Definition:
The policy mode defines the algorithm family and encapsulates them separately so that they can replace each other. This mode makes the algorithm changes independent of the customers who use the algorithm.
Scenario:
There are a wide variety of ducks, including wild ducks, rubber ducks, and bait ducks. Some of them will fly, some will not fly, some will scream, some will scream, and some will not scream. The flight behavior and scream behavior can be encapsulated as an algorithm family, so that the duck's flight behavior or scream behavior can be replaced with each other. If the duck wings are hurt, we can change the Flying Behavior of ducks so that they do not fly.
Class diagram:
The C ++ code is as follows:
#include <iostream>
using namespace std;
class FlyBehavior
{
public:
virtual void fly() = 0;
};
class FlyWithWings:public FlyBehavior
{
public:
void fly()
{
printf("I'm flying!!\n");
}
};
class FlyNoWay:public FlyBehavior
{
public:
void fly()
{
printf("I can't fly\n");
}
};
class QuackBehavior
{
public:
virtual void quack() =0;
};
class Quack:public QuackBehavior
{
public:
void quack()
{
printf("Quack\n");
}
};
class MuteQuack:public QuackBehavior
{
public:
void quack()
{
printf("<<Silence>>\n");
}
};
class Squeak:public QuackBehavior
{
public:
void quack()
{
printf("Squeak\n");
}
};
class Duck
{
public:
virtual ~Duck()
{
delete m_pFlyBehavior;
delete m_pQuackBehavior;
}
virtual void display() = 0;
void performFly()
{
if (NULL !=m_pFlyBehavior)
{
m_pFlyBehavior->fly();
}
}
void perfromQuack()
{
if (NULL != m_pQuackBehavior)
{
m_pQuackBehavior->quack();
}
}
void swim()
{
printf("All ducks float,even decoys!\n");
}
void setFlyBehavior(FlyBehavior* fb)
{
if (NULL != m_pFlyBehavior)
{
delete m_pFlyBehavior;
}
m_pFlyBehavior = fb;
}
void setQuackBehavior(QuackBehavior* qb)
{
if (NULL != m_pQuackBehavior)
{
delete m_pQuackBehavior;
}
m_pQuackBehavior = qb;
}
protected:
FlyBehavior* m_pFlyBehavior;
QuackBehavior* m_pQuackBehavior;
};
class MallardDuck:public Duck
{
public:
MallardDuck()
{
m_pFlyBehavior = new FlyWithWings();
m_pQuackBehavior = new Quack();
}
void display()
{
printf("I'm a real Mallard duck\n");
}
};
int main()
{
Duck* mallard = new MallardDuck();
mallard->performFly();
mallard->perfromQuack();
mallard->setFlyBehavior(new FlyNoWay());
printf("My wings hurt!!\n");
mallard->performFly();
delete mallard;
return 0;
}
The running result is as follows:
I'm flying !!
Quack
My wings hurt !!
I can't fly
Reference books: head first design model