[ create a new paste ] login | about

Link: http://codepad.org/uDX2Ai8V    [ raw code | output | fork ]

C++, pasted on Dec 14:
#include <vector>

using namespace std;

class IMessageListener
{
public:
	friend void SendMessage(const std::string& message);
	IMessageListener();
	virtual ~IMessageListener();
protected:
	virtual void handle(const std::string& message)=0;
	void hoge(){};
};

typedef std::vector<IMessageListener*> MessageListenerList;
typedef MessageListenerList::iterator MessageListenerListIt;

namespace {
MessageListenerList messageListenerList_;
}

IMessageListener::IMessageListener()
{
	messageListenerList_.push_back(this);
}

IMessageListener::~IMessageListener()
{
	messageListenerList_.erase(remove(messageListenerList_.begin(), messageListenerList_.end(), this), messageListenerList_.end());
}

class Hoge : public IMessageListener
{
public:
	Hoge(int value)
	: value_(value)
	{
	}
protected:
	virtual void handle(const std::string& message)
	{
		cout << "Hoge(" << value_ << ")::handle" << message << endl;
	}
private:
	int value_;
};

class Foo : public IMessageListener
{
protected:
	virtual void handle(const std::string& message)
	{
		cout << "Foo::handle:" << message << endl;
	}
};

class Bar : public IMessageListener
{
public:
	Bar()
	: foo_(new Foo())
	{
	}
        virtual ~Bar()
        {
                delete foo_;
        }
protected:
	virtual void handle(const std::string& message)
	{
		cout << "Bar::handle:" << message << endl;
	}
private:
	Foo* foo_;
};

void SendMessage(const std::string& message)
{
	for_each(
		messageListenerList_.begin(),
		messageListenerList_.end(),
		boost::bind(&IMessageListener::handle,_1,boost::ref(message))
	);
}



int main()
{
	{
		Bar bar;
		Hoge hoge(0);
		Hoge hoge2(1);
		Hoge hoge3(2);
		Hoge hoge4(3);
		Hoge hoge5(4);
		Hoge hoge6(5);

		::SendMessage("test");
                cout << "--------------------" << endl;
		::SendMessage("test2");
	}
        cout << "--------------------" << endl;
        ::SendMessage("test3");
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Bar::handle:test
Foo::handle:test
Hoge(0)::handletest
Hoge(1)::handletest
Hoge(2)::handletest
Hoge(3)::handletest
Hoge(4)::handletest
Hoge(5)::handletest
--------------------
Bar::handle:test2
Foo::handle:test2
Hoge(0)::handletest2
Hoge(1)::handletest2
Hoge(2)::handletest2
Hoge(3)::handletest2
Hoge(4)::handletest2
Hoge(5)::handletest2
--------------------


Create a new paste based on this one


Comments: