Ziyaretçi kısmen
o ziyaret etti sınıfları açarak kapsülleme bozmak gerekiyordu
- Vistor ve Ziyaret hiyerarşileri arasında
- döngüsel bağımlılık kısmen
ve iç yapıları bazı gerçek sorunlara, kötü bir üne sahiptir kapalı bir hiyerarşiye sanal işlevler eklemek yerine bir yapının geçişini vurgulayan GOF kitabındaki sergiden dolayı. Bu, uygun olduğunda, örneğin, statik olarak yazılan dillerde çift gönderim sorununu çözmek için dikkate alınmadığı anlamına gelir. Örnek: İleti türlerinin sabit olduğu C++ 'da bir ileti veya olay geçirme sistemi, ancak yeni alıcılar ekleyerek genişletmek istiyoruz. Burada mesajlar sadece yapıdır, bu yüzden onları içine almayı umursamıyoruz. SendTo()
, Message
veya MessageRecipient
'un ne tür olduğunu bilmiyor.
#include <iostream>
#include <ostream>
using namespace std;
// Downside: note the cyclic dependencies, typically expressed in
// real life as include file dependency.
struct StartMessage;
struct StopMessage;
class MessageRecipient
{
public:
// Downside: hard to add new messages
virtual void handleMessage(const StartMessage& start) = 0;
virtual void handleMessage(const StopMessage& stop) = 0;
};
struct Message
{
virtual void dispatchTo(MessageRecipient& r) const = 0;
};
struct StartMessage : public Message
{
void dispatchTo(MessageRecipient& r) const
{
r.handleMessage(*this);
}
// public member data ...
};
struct StopMessage : public Message
{
StopMessage() {}
void dispatchTo(MessageRecipient& r) const
{
r.handleMessage(*this);
}
// public member data ...
};
// Upside: easy to add new recipient
class RobotArm : public MessageRecipient
{
public:
void handleMessage(const StopMessage& stop)
{
cout << "Robot arm stopped" << endl;
}
void handleMessage(const StartMessage& start)
{
cout << "Robot arm started" << endl;
}
};
class Conveyor : public MessageRecipient
{
public:
void handleMessage(const StopMessage& stop)
{
cout << "Conveyor stopped" << endl;
}
void handleMessage(const StartMessage& start)
{
cout << "Conveyor started" << endl;
}
};
void SendTo(const Message& m, MessageRecipient& r)
{
// magic double dispatch
m.dispatchTo(r);
}
int main()
{
Conveyor c;
RobotArm r;
SendTo(StartMessage(), c);
SendTo(StartMessage(), r);
SendTo(StopMessage(), r);
}