• wxpython之pubsub 发布订阅者模式


    wxPython Pubsub 包提供的发布-订阅模式,允许您的应用程序的不同部分之间发送数据。在许多情况下,使用发布-订阅者模式,将大大简化其设计复杂度和提高可测试性。罗宾 · 邓恩,创建者的 wxPython,优雅的对Pubsub描述:

      基本上你的程序的一些部件订阅特定的主题,然后其它部件发布该主题的消息。

    图解:

    Publisher基本用法:

    pub.subscribe(listener, topic):listener订阅者,这边一般是函数。topic,uniqu的主题。

    sendMessage(topic, data, onTopicNeverCreated):topic,uniqu的主题,data 要传给订阅者的数据。onTopicNeverCreated如果没有这个主题被订阅,应该有onTopicNeverCreated处理

    例子:

    #-*- coding: UTF-8 -*-
    #-------------------------------------------------------------------------------
    # Name:        
    # Purpose:     
    #
    # Author:      ankier
    #
    # Created:     12-01-2013
    # Copyright:   (c) ankier 2013
    # Licence:     <your licence>
    #-------------------------------------------------------------------------------
    
    from wx.lib.pubsub import Publisher as pub
    
    class Student():
        def __init__(self):
            self.__Name = None        
            #注册订阅事件
            pub.subscribe(self.__UpdateName,  'nameEvntTopic')
        
        def SetName(self, name):
            self.__Name = name
         
        #订阅事件    
        def __UpdateName(self, eventTopicData):
            if self.__Name == 'NameA':
                print 'You can not give me a new name as my name is ',self.__Name
                return
            else:
                print 'I change name to ', eventTopicData.data
            self.__Name = eventTopicData.data    
    
    stuA = Student()
    stuA.SetName('NameA')
    stuB = Student()
    stuB.SetName('NameB')
    
    #发布消息
    pub.sendMessage('nameEvntTopic', ['NewName', 'Age'])
    
    #事件没有被注册时候,统一转到该函数处理
    def onTopicNeverCreated(eventTopicData):
        print eventTopicData
    
    #发布一个不存在的事件
    pub.sendMessage('NoneEvntTopic', ['NewName', 'Age'], onTopicNeverCreated)

    运行结果:

    You can not give me a new name as my name is  NameA
    I change name to  ['NewName', 'Age']
    ('NoneEvntTopic',)
  • 相关阅读:
    JavaOne Online Hands-on Labs
    Using DTrace to Profile and Debug A C++ Program
    怎样挑选电线?家装用线越大越好吗?
    ORACLE DTRACE DOC
    内核书
    SQL Server vNext CTP 1.2
    用VS Code打造最佳Markdown编辑器
    opendtrace 开源汇总
    DTrace C++ Mysteries Solved 转
    MYSQL-RJWEB 博客学习
  • 原文地址:https://www.cnblogs.com/ankier/p/2857648.html
Copyright © 2020-2023  润新知