策略模式(Strategy)

类图:

未命名

#ifndef STRATEGY_H
#define STRATEGY_H

#include

using namespace std;

class FlyBehavior
{
public:
    virtual void fly() = 0;
};

class FlyWithWings : public FlyBehavior
{
public:
    virtual void fly()
    {
        cout << "fly with wings" << endl;
    }
};

class FlyNoWay : public FlyBehavior
{
public:
    virtual void fly()
    {
        cout << "fly no way" << endl;
    }
};

class QuackBehavior
{
public:
    virtual void quack() = 0;
};

class Quack : public QuackBehavior
{
public:
    virtual void quack()
    {
        cout << "quack" << endl;
    }
};

class Squeak : public QuackBehavior
{
public:
    virtual void quack()
    {
        cout << "squeak" << endl;
    }
};

class MuteQuack : public QuackBehavior
{
public:
    virtual void quack()
    {
    cout << "mute quack" << endl;
    }
};

class Duck
{
public:
    FlyBehavior *flyBehavior;
    QuackBehavior *quackBehavior;

public:
    void swim()
    {
        cout << "swim" << endl;
    }
    virtual void display();
    void performQuack()
    {
        quackBehavior->quack();
    }
    void performFly()
    {
        flyBehavior->fly();
    }
    void setFlyBehavior(FlyBehavior *fb)
    {
        flyBehavior = fb;
    }
    void setQuackBehavior(QuackBehavior *qb)
    {
        quackBehavior = qb;
    }
};

class MallardDuck : public Duck
{
public:
    MallardDuck()
    {
        quackBehavior = new Quack();
        flyBehavior = new FlyWithWings();
    }
public:
    virtual void dipslay()
    {
        cout << "mallard duck" << endl;
    }
};

class RedHeadDuck : public Duck
{
public:
    RedHeadDuck()
    {
        quackBehavior = new Quack();
        flyBehavior = new FlyWithWings();
    }
public:
    virtual void dipslay()
    {
        cout << "RedHead duck" << endl;
    }
};

class RubberDuck : public Duck
{
public:
    RubberDuck()
    {
        quackBehavior = new Quack();
        flyBehavior = new FlyWithWings();
    }
public:
    virtual void dipslay()
    {
        cout << "Rubber duck" << endl;
    }
};

class DecoyDuck : public Duck
{
public:
    DecoyDuck()
    {
        quackBehavior = new Quack();
        flyBehavior = new FlyWithWings();
    }
public:
    virtual void dipslay()
    {
        cout << "Decoy duck" << endl;
    }
};

#endif

阅读更多
文章标签: class
个人分类: 设计模式
上一篇连连看
下一篇企鹅的故事
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭