-----------------------------------------------------------------------------
[Mediator]
의도:
객체들 간의 상호작용을 캡슐화하여 하나의 객체 안에 정의한다. Mediator 패턴은 각 객체가
관련성을 갖는 다른 객체에 대한 참조 관계를 직접 정의하기보다는 이를 독립된 다른 객체가
관리하게 한다.
-----------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////
//
// A Behavioral part of GoF's Design Patterns
//
// - Mediator
//
/////////////////////////////////////////////////////////////////////////////
#include <windows.h>
#include <tchar.h>
#include <iostream>
#include <memory>
/////////////////////////////////////////////////////////////////////////////
//
// Mediator
//
//
/////////////////////////////////////////////////////////////////////////////
class Colleague;
class Mediator
{
public:
virtual ~Mediator () {}
public:
virtual void OnNotify (Colleague *) {}
};
class Colleague
{
public:
Colleague (Mediator* m) : Mediator_(m) {}
virtual ~Colleague () {}
public:
virtual void Notify ()
{
if (Mediator_)
{
Mediator_->OnNotify (this);
}
}
protected:
Mediator* Mediator_;
};
////-------------------------------------------------------------------------
class ConcreteColleague1 : public Colleague
{
public:
ConcreteColleague1 (Mediator* m) : Colleague (m) {}
public:
void Act1 (void)
{
Notify ();
}
};
class ConcreteColleague2 : public Colleague
{
public:
ConcreteColleague2 (Mediator* m) : Colleague (m) {}
public:
void Act2 (void)
{
Notify ();
}
};
class ConcreteMediator : public Mediator
{
public:
void Init (void)
{
Colleague1_.reset ( new ConcreteColleague1(this) );
Colleague2_.reset ( new ConcreteColleague2(this) );
}
void Run (void)
{
Colleague1_->Act1 ();
Colleague2_->Act2 ();
}
virtual void OnNotify (Colleague *c)
{
if (c==Colleague1_.get())
{
std::cout << "ConcreteMediator::OnNotify() = Colleague1_" << std::endl;
}
else if (c==Colleague2_.get())
{
std::cout << "ConcreteMediator::OnNotify() = Colleague2_" << std::endl;
}
}
private:
std::auto_ptr<ConcreteColleague1> Colleague1_;
std::auto_ptr<ConcreteColleague2> Colleague2_;
};
/////////////////////////////////////////////////////////////////////////////
//
// Startup
//
//
/////////////////////////////////////////////////////////////////////////////
int _tmain(int argc, _TCHAR* argv[])
{
ConcreteMediator mediator;
mediator.Init ();
mediator.Run ();
return 0;
}
-----------------------------------------------------------------------------
ConcreteMediator::OnNotify() = Colleague1_
ConcreteMediator::OnNotify() = Colleague2_