关于成员函数的Command模式的简单实现

看到Fox发表关于成员函数的消息映射的文章,也忍不住发表的一点自己的观点,希望对大家有所帮助。

其实也就是COMMAND模式的简单实现,看代码吧。

  1. XGUIEventHandlerPointer.h
namespace XGUI

{

    class EventHandlerSlot

    {

    public:

        virtual ~EventHandlerSlot() {};

        virtual void execute(const EventArgs& args) = 0;

        virtual void* getClass() = 0;

    };


    template<typename T>

    class EventHandlerPointer :

        public EventHandlerSlot

    {

    public:

        typedef void (T::*EventHandler)(const EventArgs&);

    public:

        EventHandlerPointer() :

            d_undefined(true),

            d_object(NULL)

        {}

        EventHandlerPointer(EventHandler func, T* obj) :

            d_function(func),

            d_object(obj),

            d_undefined(false)

        {}

        virtual ~EventHandlerPointer() {}


        void execute(const EventArgs& args)

        {

            if(!d_undefined) 

                (d_object->*d_function)(args);

        }


        void* getClass()

        {

            return static_cast<void*>(d_object);

        }


    protected:

        EventHandler    d_function;

        T*                d_object;

        bool            d_undefined;

    };

}


  1. XGUIWidget.h

 

namespace XGUI

{

    // 

    class Widget

    {

    public:

        template<typename T> void addWidgetEventHandler(WidgetEvent EVENT, void (T::function)(const EventArgs&), T obj)

        {

            mWidgetEventHandlers[EVENT].push_back(new EventHandlerPointer<T>(function,obj));

        }

        void addWidgetEventHandler(WidgetEvent EVENT, EventHandlerSlot* function)

                {

            mWidgetEventHandlers[EVENT].push_back(new EventHandlerPointer<T>(function,obj));

        }

                bool Widget::fireWidgetEvent(WidgetEvent EVENT, EventArgs& args)

                {

                      // If there are no User defined event handlers we are done.

                      if(mWidgetEventHandlers[EVENT].empty())

                       return false;

                    

                      // Execute registered handlers

                      std::vector<EventHandlerSlot> userEventHandlers = &(mWidgetEventHandlers[EVENT]);

                      for(std::vector<EventHandlerSlot*>::iterator it = userEventHandlers->begin(); it != userEventHandlers->end(); ++it )

                       (*it)->execute(args);

                    

                      return true;

             }

        // .

    };

}


以上只为部分代码。