码迷,mamicode.com
首页 > 其他好文 > 详细

模拟C#的事件处理和属性语法糖

时间:2014-09-13 17:07:06      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   io   os   ar   for   2014   art   

1. [代码]SharpEvent.hpp     

/*
 * SharpEvent.hpp
 *
 *  Created on: 2014-5-5
 *      Author: leoking
 *   Copyright: This file is published under BSD license.
 *
    Copyright (c) <2014>, <leoking>
    All rights reserved.
 
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
        * Redistributions of source code must retain the above copyright
          notice, this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright
          notice, this list of conditions and the following disclaimer in the
          documentation and/or other materials provided with the distribution.
        * Neither the name of the <organization> nor the
          names of its contributors may be used to endorse or promote products
          derived from this software without specific prior written permission.
 
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
 
#ifndef SHARPEVENT_HPP_
#define SHARPEVENT_HPP_
 
#include <list>
#include <stdexcept>
 
namespace SharpEvent
{
    template<typename SenderT, typename EventArgsT>
    class CEventHandler
    {
    public:
        typedef SenderT     SenderType;
        typedef EventArgsT  EventArgsType;
 
    private:
        struct holder
        {
            virtual ~holder() {}
            virtual holder* clone() const = 0;
            virtual bool equals(const holder*) const = 0;
            virtual void invoke(SenderType, EventArgsType) const = 0;
        };
 
        struct fholder : public holder
        {
            typedef void (*function)(SenderType, EventArgsType);
            function func;
            fholder(function f) : func(f) {}
            virtual holder* clone() const { return new fholder(func); }
            virtual bool equals(const holder* rhs) const {
                const fholder* p = dynamic_cast<const fholder*>(rhs);
                if (p)
                    return func == p->func;
                else
                    return false;
            }
            virtual void invoke(SenderType a0, EventArgsType a1) const { (*func)(a0, a1); }
        };
 
        template<typename C>
        struct mholder : public holder
        {
            typedef C concept_t;
            typedef void (concept_t::*function)(SenderType, EventArgsType);
            concept_t& obj;
            function func;
            mholder(concept_t* o, function f) : obj(*o), func(f) {}
            virtual holder* clone() const { return new mholder(&obj, func); }
            virtual bool equals(const holder* rhs) const {
                const mholder* p = dynamic_cast<const mholder*>(rhs);
                if (p)
                    return &obj == &(p->obj) && func == p->func;
                else
                    return false;
            }
            virtual void invoke(SenderType a0, EventArgsType a1) const { (obj.*func)(a0, a1); }
        };
 
        holder* h;
 
    public:
        CEventHandler() : h(0) {}
 
        CEventHandler(void(*function)(SenderType, EventArgsType)) : h(0) {
            if (function)
                h = new fholder(function);
        }
 
        template<typename Concept>
        CEventHandler(Concept* object, void(Concept::*function)(SenderType, EventArgsType)) : h(0) {
            if (object && function)
                h = new mholder<Concept>(object, function);
        }
 
        CEventHandler(const CEventHandler& rhs) : h(0) {
            if (rhs.h)
                h = rhs.h->clone();
        }
 
        ~CEventHandler() { delete h; }
 
        void Assign(void(*function)(SenderType, EventArgsType)) {
            Clear();
            if (function)
                h = new fholder(function);
        }
 
        template<typename Concept>
        void Assign(Concept* object, void(Concept::*function)(SenderType, EventArgsType)) {
            Clear();
            if (object && function)
                h = new mholder<Concept>(object, function);
        }
 
        void Assign(const CEventHandler& rhs) {
            if (Equals(rhs))
                return;
            Clear();
            if (rhs.h)
                h = rhs.h->clone();
        }
 
        void Clear() {
            delete h;
            h = 0;
        }
 
        bool Empty() const { return h == 0; }
 
        bool Equals(const CEventHandler& rhs) const {
            if (h && rhs.h)
                return h->equals(rhs.h);
            return false;
        }
 
        void Invoke(SenderType sender, EventArgsType e) const {
            if (h)
                h->invoke(sender, e);
            else
                throw std::runtime_error("Empty EventHandler invoked.");
        }
 
        CEventHandler& operator=(const CEventHandler& rhs) { Assign(rhs); return *this; }
 
        bool operator==(const CEventHandler& rhs) { return Equals(rhs); }
 
        void operator()(SenderType sender, EventArgsType e) const { Invoke(sender, e); }
    };
 
    template<typename DelegateType>
    class CEvent
    {
    public:
        typedef DelegateType EventHandlerType;
        typedef typename EventHandlerType::SenderType       SenderType;
        typedef typename EventHandlerType::EventArgsType    EventArgsType;
 
        CEvent() {}
 
        void operator+=(EventHandlerType handler) { handlers.push_front(handler); handlers.unique(); }
        void operator-=(EventHandlerType handler) { handlers.remove(handler); }
 
        void operator()(SenderType sender, EventArgsType e) {
            for (typename std::list<EventHandlerType>::const_iterator it = handlers.begin();
                    it != handlers.end(); it++)
            {
                EventHandlerType handler = *it;
                handler.Invoke(sender, e);
            }
        }
 
    private:
        std::list<EventHandlerType> handlers;
 
    private:
        CEvent(const CEvent&);
        void operator=(const CEvent&);
    };
}
 
 
#endif /* SHARPEVENT_HPP_ */
2. [代码]SharpProperty.hpp     

/*
 * SharpProperty.hpp
 *
 *  Created on: 2014-5-8
 *      Author: leoking
 *   Copyright: This file is published under BSD license.
 *  
    Copyright (c) <2014>, <leoking>
    All rights reserved.
 
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
        * Redistributions of source code must retain the above copyright
          notice, this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright
          notice, this list of conditions and the following disclaimer in the
          documentation and/or other materials provided with the distribution.
        * Neither the name of the <organization> nor the
          names of its contributors may be used to endorse or promote products
          derived from this software without specific prior written permission.
 
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
#ifndef SHARPPROPERTY_HPP_
#define SHARPPROPERTY_HPP_
 
#include <stdexcept>
 
namespace SharpProperty
{
    template<typename T>
    class CGetter
    {
    public:
        typedef T ValueType;
 
    private:
        struct holder
        {
            virtual ~holder() {}
            virtual holder* clone() const = 0;
            virtual bool equals(const holder*) const = 0;
            virtual ValueType invoke() const = 0;
        };
 
        struct fholder : public holder
        {
            typedef ValueType(*function)();
            function func;
            fholder(function f) : func(f) {}
            virtual holder* clone() const { return new fholder(func); }
            virtual bool equals(const holder* rhs) const {
                const fholder* p = dynamic_cast<const fholder*>(rhs);
                if (p)
                    return p->func == func;
                else
                    return false;
            }
            virtual ValueType invoke() const { return (*func)(); }
        };
 
        template<typename Concept>
        struct mholder : public holder
        {http://www.huiyi8.com/hehua/
            typedef Concept concept;?荷花
            typedef ValueType(concept::*function)();
            concept& object;
            function func;
            mholder(concept* o, function f) : object(*o), func(f) {}
            virtual holder* clone() const { return new mholder(&object, func); }
            virtual bool equals(const holder* rhs) const {
                const mholder* p = dynamic_cast<const mholder*>(rhs);
                if (p)
                    return &(p->object) == &object && p->func == func;
                else
                    return false;
            }
            virtual ValueType invoke() const { return (object.*func)(); }
        };
 
        holder* h;
 
    public:
        CGetter(ValueType (*function)()) : h(0) {
            if (function)
                h = new fholder(function);
        }
 
        template<typename Concept>
        CGetter(Concept* object, ValueType(Concept::*function)()) : h(0) {
            if (object && function)
                h = new mholder<Concept>(object, function);
        }
 
        CGetter(const CGetter& rhs) {
            if (rhs.h)
                h = rhs.h->clone();
        }
 
        ~CGetter() { delete h; }
 
        ValueType Invoke() const {
            if (h)
                return h->invoke();
            else
                throw std::runtime_error("Empty Getter invoked.");
        }
 
    private:
        void operator=(const CGetter&);
    };
 
    template<typename T>
    class CSetter
    {
    public:
        typedef T ValueType;
 
    private:
        struct holder
        {
            virtual ~holder() {}
            virtual holder* clone() const = 0;
            virtual bool equals(const holder*) const = 0;
            virtual void invoke(ValueType) const = 0;
        };
 
        struct fholder : public holder
        {
            typedef void(*function)(ValueType);
            function func;
            fholder(function f) : func(f) {}
            virtual holder* clone() const { return new fholder(func); }
            virtual bool equals(const holder* rhs) const {
                const fholder* p = dynamic_cast<const fholder*>(rhs);
                if (p)
                    return p->func == func;
                else
                    return false;
            }
            virtual void invoke(ValueType value) const { (*func)(value); }
        };
 
        template<typename Concept>
        struct mholder : public holder
        {
            typedef Concept concept;
            typedef void(concept::*function)(ValueType);
            concept& object;
            function func;
            mholder(concept* o, function f) : object(*o), func(f) {}
            virtual holder* clone() const { return new mholder(&object, func); }
            virtual bool equals(const holder* rhs) const {
                const mholder* p = dynamic_cast<const mholder*>(rhs);
                if (p)
                    return &(p->object) == &object && p->func == func;
                else
                    return false;
            }
            virtual void invoke(ValueType value) const { (object.*func)(value); }
        };
 
        holder* h;
 
    public:
        CSetter(void (*function)(ValueType)) : h(0) {
            if (function)
                h = new fholder(function);
        }
 
        template<typename Concept>
        CSetter(Concept* object, void(Concept::*function)(ValueType)) : h(0) {
            if (object && function)
                h = new mholder<Concept>(object, function);
        }
 
        CSetter(const CSetter& rhs) {
            if (rhs.h)
                h = rhs.h->clone();
        }
 
        ~CSetter() { delete h; }
 
        void Invoke(ValueType value) const {
            if (h)
                h->invoke(value);
            else
                throw std::runtime_error("Empty Setter invoked.");
        }
 
    private:
        void operator=(const CSetter&);
    };
 
    template<typename T>
    class property
    {
    public:
        typedef T ValueType;
 
        property() : getter(0), setter(0) {}
        ~property() { delete getter; delete setter; }
 
        void operator()(ValueType (*getter)(), void (*setter)(ValueType)) {
            if (getter)
                this->getter = new CGetter<ValueType>(getter);
            if (setter)
                this->setter = new CSetter<ValueType>(setter);
        }
 
        void operator()(ValueType (*getter)()) {
            this->operator()(getter, 0);
        }
 
        void operator()(void (*setter)(ValueType)) {
            this->operator()(0, setter);
        }
 
        template<typename Concept>
        void operator()(Concept* object, ValueType (Concept::*getter)(), void (Concept::*setter)(ValueType)) {
            if (object == 0)
                throw std::invalid_argument("Property initialized with null object.");
            if (getter)
                this->getter = new CGetter<ValueType>(object, getter);
            if (setter)
                this->setter = new CSetter<ValueType>(object, setter);
        }
 
        template<typename Concept>
        void operator()(Concept* object, ValueType (Concept::*getter)()) {
            this->operator()<Concept>(object, getter, 0);
        }
 
        template<typename Concept>
        void operator()(Concept* object, void (Concept::*setter)(ValueType)) {
            this->operator()<Concept>(object, 0, setter);
        }
 
        operator ValueType() {
            if (getter == 0)
                throw std::runtime_error("Property without getter is not readable.");
            return getter->Invoke();
        }
 
        void operator=(ValueType value) {
            if (setter == 0)
                throw std::runtime_error("Property without setter is not assignable.");
            setter->Invoke(value);
        }
 
    private:
        CGetter<ValueType>* getter;
        CSetter<ValueType>* setter;
 
        property(const property&);
    };
}
 
#endif /* SHARPPROPERTY_HPP_ */
3. [代码]Sample.cpp     

#include "SharpEvent.hpp"
#include "SharpProperty.hpp"
#include <string>
#include <iostream>
 
class CPerson;
 
using SharpProperty::property;
typedef SharpEvent::CEventHandler<CPerson*, double> EventHandler;
typedef SharpEvent::CEvent<EventHandler> event;
 
class CPerson
{
public:
    // enum:
    enum SexFlag { FEMALE, MALE };
     
    CPerson(const std::string& name, int age, SexFlag sex, double tall)
        : name(name), age(age), sex(sex), tall(tall)
    {
        Name(this, &CPerson::getName, &CPerson::setName);
        Age(this, &CPerson::getAge, &CPerson::setAge);
        Sex(this, &CPerson::getSex); // Sex property can not be modified.
        Tall(this, &CPerson::getTall, &CPerson::setTall);
    }
     
    // property:
    property<std::string> Name;
    property<int> Age;
    property<SexFlag> Sex;
    property<double> Tall;
     
    // event:
    event Growth;
         
private:
    // field:
    std::string name;
    int age;
    SexFlag sex;
    double tall;
     
    // getter-setter:
    std::string getName() { return name; }
    void setName(std::string value) { name = value; }
     
    int getAge() { return age; }
    void setAge(int value) { age = value; }
     
    SexFlag getSex() { return sex; }
    //void setSex(SexFlag value) { sex = value; }
     
    double getTall() { return tall; }
    void setTall(double value) {
        tall = value;
        Growth(this, tall);
    }
};
 
void OnGrowth(CPerson* sender, double e) {
    std::cout << "Person named " << (std::string)sender->Name
            << " has grown to " << e << " cm."
            << std::endl;
}
 
int main()
{
    CPerson person("LiMing", 20, CPerson::MALE, 173.4);
    person.Growth += EventHandler(&OnGrowth);
    person.Tall = 174;
}

模拟C#的事件处理和属性语法糖

标签:style   http   color   io   os   ar   for   2014   art   

原文地址:http://www.cnblogs.com/xkzy/p/3969888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!