如何将消息“广播”到类的所有对象?

时间:2014-12-22 11:49:29

标签: python

class Person:
    def __init__(self, name):
        self.name = name
        self.bucket = []
    def announce(self, *args):
        # ???
        pass
    def put(self, item):
        self.bucket.append(item)


p1 = Person("ya")
p2 = Person("yu")

p1.put("apple")

现在我想以某种方式向所有Person()对象宣布我的桶中有一个苹果,如果他们想要的话,他们也应该在他们的桶中放一个苹果。

3 个答案:

答案 0 :(得分:3)

简单的实施可能是:

class Person:
    persons = set()

    def __init__(self, name):
        self.name = name
        self.bucket = []
        self.persons.add(self)

    def announce(self, msg):
        print("[{}]: {}".format(self.name,msg))

    @classmethod
    def broadcast(cls, person, msg):
        for p in cls.persons:
            if not p is person:
                p.announce(msg)

    def put(self, item):
        self.bucket.append(item)
        self.broadcast(self, '{}: got {} in my bucket!'.format(self.name, item))

p1 = Person("ya")
p2 = Person("yu")

p1.put("apple")
Person.broadcast(None, "Hey! Everybody can broadcast message!")

输出:

[yu]: "ya: got apple in my bucket!
[ya]: Hey! Everybody can broadcast message!
[yu]: Hey! Everybody can broadcast message!

该实施缺乏

  • deregister实施
  • 无线程保存
  • 只需Person即可通知其子类
  • 这只是一个玩具,你需要根据你的真实情况进行调整

也许比简单的更好地实现Observer pattern

答案 1 :(得分:1)

在python中实现observer-pattern非常简单, 基本思想"我想要对象A,对象B,对象C从指定的消息传递对象获取通知"。因此,你以某种方式必须连接它们,在观察者模式中这个过程称为" subscription"。所以你的对象A,B,C(观察者)正在订阅传递消息的对象(主题) 此示例是基本实现。我没有把它添加到你的代码中,但alice和bob在你的情况下就是人。

class Mailbox :
    def __init__(self, ownersName):
        self.owner = ownersName
        self.messages = []
        self.newMessageObservers = []

    def deliverMessage(self, message):
        self.messages.append(message)
        for notifyNewMessage in self.newMessageObservers:
            notifyNewMessage(message, self.owner)

    def subscribe(self, observer):
        self.newMessageObservers.append(observer) 

class MailboxObserver :
    def __init__(self, observerName):
        self.name = observerName

    def newMessageHandler(self, contents, owner):
        print self.name + " observed a new message in " +\
              owner + "'s mailbox"
        print "The message said: " + contents


# create the observers
alice = MailboxObserver("alice")
bob = MailboxObserver("bob")

# create a mailbox
alicesMailbox = Mailbox("alice")

# have bob and alice subscribe to alice's mailbox
# registering their 'newMessageHandler' method
alicesMailbox.subscribe(bob.newMessageHandler)
alicesMailbox.subscribe(alice.newMessageHandler)

# put a new message into alice's mailbox
alicesMailbox.deliverMessage("Hello, world!")

来源:http://www.philipuren.com/serendipity/index.php?/archives/4-Simple-Observer-Pattern-in-Python.html

答案 2 :(得分:0)

只需在您的班级中保留一个普通变量(不是会员),并在您想要向所有班级“宣布”某些内容时更新它。

class Person:
    bApple = False

    def __init__(self, name):
        self.name = name
        self.bucket = []
    def announce(self, *args):
        # ???
        pass
    def put(self, item):
        self.bucket.append(item)

    def hasApple(self):
        if Person.bApple:
            return "True"
        else:
            return "False"


p1 = Person("ya")
p2 = Person("yu")

p1.put("apple")

print "p1 has Apple? " + p1.hasApple()
print "p2 has Apple? " + p2.hasApple()

Person.bApple = True

print "p1 has Apple? " + p1.hasApple()
print "p2 has Apple? " + p2.hasApple()