用C++模拟Java的事件机制

11 篇文章 0 订阅
10 篇文章 0 订阅
代码很简单,无需注释

Author: Kevin Yin

#include <iostream>

using namespace std;

class KeyPressEvent
{
private:
    int _refCount;
public:
    KeyPressEvent()
    {
        _refCount = 0;
    }

    virtual void KeyDown(int a)=0;
    virtual void KeyUp(int a)=0;
    virtual void KeyPress(int a)=0;
    void AddRef()
    {
        _refCount++;   
    }

    void RemoveRef()
    {
        _refCount--;
    }
   
    int GetRefCount()
    {
        return _refCount;
    }

};


class Window
{
protected:
    KeyPressEvent *KeyPressListener;
public:
    void AddKeyPressListener(KeyPressEvent *kpe)
    {
        KeyPressListener = kpe;
        KeyPressListener->AddRef();
    }

    void RemoveKeyPressListener()
    {
        KeyPressListener->RemoveRef();
        KeyPressListener = NULL;
    }

    ~Window()
    {
        if (KeyPressListener != NULL){
            KeyPressListener->RemoveRef();
            if ( KeyPressListener->GetRefCount() == 1 ){
                delete KeyPressListener;
            }
        }
    }
};

class Windows2 : public Window
{
private:
    class KeyKey : public KeyPressEvent
    {
        void KeyDown(int a)
        {
            cout<<"Key Down"<<endl;
        }

        void KeyUp(int a)
        {
            cout<<"Key Up"<<endl;
        }

        void KeyPress(int a)
        {
            cout<<"Key Press"<<endl;
        }
    };
public:
    Windows2()
    {
        AddKeyPressListener(new KeyKey());
    }
   
    void Do()
    {
        if (KeyPressListener != NULL){
            cout<<KeyPressListener->GetRefCount()<<endl;
            KeyPressListener->KeyDown(1);
            KeyPressListener->KeyUp(2);
            KeyPressListener->KeyPress(3);
        }
    }
};


class KeyKey2 : public KeyPressEvent
    {
        void KeyDown(int a)
        {
            cout<<"Key Down"<<endl;
        }

        void KeyUp(int a)
        {
            cout<<"Key Up"<<endl;
        }

        void KeyPress(int a)
        {
            cout<<"Key Press"<<endl;
        }
    };

class Windows3 : public Window
{
public:
    Windows3()
    {}
   
    void Do()
    {
        if (KeyPressListener != NULL){
            cout<<KeyPressListener->GetRefCount()<<endl;
            KeyPressListener->KeyDown(1);
            KeyPressListener->KeyUp(2);
            KeyPressListener->KeyPress(3);
        }
    }
};

int main()
{
    Windows2 win;
    win.Do();

    Windows3 win3;
    win3.AddKeyPressListener(new KeyKey2());
    win3.Do();

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值