软件体系结构 观察者模式Python实现

class Publisher:
    def __init__(self):
        pass

    def register(self):
        pass

    def unregister(self):
        pass

    def notifyAll(self):
        pass

class TechForum(Publisher):
    def __init__(self):
        self._listOfUsers = []
        self.postname = None
    def register(self, userObj):
        if userObj not in self._listOfUsers:
                self._listOfUsers.append(userObj)

    def unregister(self, userObj):
        self._listOfUsers.remove(userObj)

    def notifyAll(self):
        for objects in self._listOfUsers:
            objects.notify(self.postname)
    
    def lognotify(self):
        for objects in self._listOfUsers:
            if(objects.flag == 1):
                objects.lognotify(self.postname)
            
    def countnotify(self):
        for objects in self._listOfUsers:
            if(objects.flag == 0):
                objects.countnotify(self.postname)
    
    def writeNewPost(self , postname):
        self.postname = postname
        self.notifyAll()
        
    def add(self,postname):
        self.postname=postname
        print("我增加了一条微博%s,被日志构件记录" % self.postname)
        self.lognotify()
        
        
    def delete(self,postname):
        self.postname=postname
        print("我删除了一条微博%s, 被日志构件记录" % self.postname)
        self.lognotify()
        
    def find(self,postname):
        self.postname = postname
        print("我查看了一条微博%s,被计数构件记录" % self.postname)
        self.countnotify()
        


class Subscriber:
    def __init__(self):
        pass

    def notify(self):
        pass


class logObserver(Subscriber):
    flag = 1
    def notify(self, postname):
        print("日志构件已经开始观察%s" % postname)
    def lognotify(self,postname):
        print("%s记录成功" %postname)
        file = open('log.txt', 'a')
        file.write(postname+'\n')
        file.close()
        


class countObserver(Subscriber):
    flag = 0
    def notify(self, postname):
        print("计数构件已经开始观察%s" % postname)
    def countnotify(self,postname):
        print("%s记录成功" %postname)
        file = open('count.txt', 'a')
        file.write(postname+'\n')
        file.close()




if __name__ == "__main__":
    
    log1 = logObserver()
    count1 = countObserver()
    
    weibo1 = TechForum()
    weibo1.register(log1)
    weibo1.register(count1)

    weibo1.writeNewPost("刘广泽的微博")
    weibo1.add("123")
    weibo1.delete("345")
    weibo1.find("hhh")
    
    #weibo1.unregister(count1)
    #weibo1.writeNewPost("郑言的微博")

实现了一个观察者模式


结构图如上:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值