模板实现策略模式

来源:互联网 发布:做海报的软件 编辑:程序博客网 时间:2024/05/22 06:06

#include "stdafx.h"
#include <iostream>

using namespace std;

class Boy
{
public:
    friend ostream& operator<<(ostream& os, const Boy&)
    {
        return os<<"Patrick";
    }
};

class Bear
{
public:
    friend ostream& operator<<(ostream& os, const Bear&)
    {
        return os<<"Theodore";
    }
};

class Feed
{
public:
    static const char* doAction()
    {
        return "Feeding";
    }
};

class Stuff
{
public:
    static const char* doAction()
    {
        return "Stuffing";
    }
};


// 模板类
template<class Guest, class Action>
class BearConer
{
    Guest theGuest;

public:
    BearConer(const Guest& g): theGuest(g) { }

    void entertain()
    {
        cout<<Action::doAction()<<" With "<<theGuest<<std::endl;
    }
};


int main()
{
    Boy cr;
    BearConer<Boy, Feed> pr1(cr);
    pr1.entertain();

    Bear br;
    BearConer<Bear, Stuff> pt1(br);
    pt1.entertain();

    system("pause");
    return 0;
}
0 0
原创粉丝点击