本文共 3203 字,大约阅读时间需要 10 分钟。
概要class Device {public: virtual void PowerOn() = 0; virtual void PowerOff() = 0; virtual void ConnectNetwork() = 0; virtual void DisconnectNetwork() = 0;};Class MobilePhone : public Device {public: virtual void PowerOn() { ...... } virtual void PowerOff() { ...... } virtual void ConnectNetwork() { ...... } virtual void DisconnectNetwork() { ...... }};
class IVisitor{public: virtual void Visit(const MobilePhone*) = 0; virtual void Visit(const PC*) = 0; virtual void Visit(const Pad*) = 0;};class PowerOnWithNetwork : public IVisitor{public: virtual void Visit(const MobilePhone*) { MobilePhone->PowerOn(); MobilePhone->ConnectNetwork(); } virtual void Visit(const PC*) { MobilePhone->PowerOn(); MobilePhone->ConnectNetwork(); } virtual void Visit(const Pad*) { MobilePhone->PowerOn(); MobilePhone->ConnectNetwork(); }};class IElement {public: virtual void Accept(IVisitor* visitor) = 0;};Class MobilePhone : public Device, public IElement {public: virtual void PowerOn() { ...... } virtual void PowerOff() { ...... } virtual void ConnectNetwork() { ...... } virtual void DisconnectNetwork() { ...... } virtual void Accept(IVisitor* visitor) { visitor->Visit(this); }};Class PC: public Device, public IElement {public: ...... virtual void Accept(IVisitor* visitor) { visitor->Visit(this); }};Class Pad: public Device, public IElement {public: ...... virtual void Accept(IVisitor* visitor) { visitor->Visit(this); }};
IVisitor* visitor = new PowerOnWithNetwork();MobilePhone* phone = new MobilePhone();phone->Accept(visitor);
转载地址:http://hceqj.baihongyu.com/