面向对象的设计方法是将研究对象抽象为类,从中提取研究对象共有的方法和属性,从而高效的实现代码复用。
消息的订阅与发布可以抽象为以下的几种基类:
消息类:定义消息的类型(标题、内容、长度等等),消息的输出函数;
发布器:消息的打印,处理;
订阅器:订阅者的增删改查;
class News():
def __init__(self,name,title,kind,content):
self.name=name
self.title=title
self.kind=kind
self.content=content
def printf(self):
print("姓名:{} 标题:{} 类型:{} 内容:{}".format(self.name,self.title,self.kind,self.content))
class Subscriber():
def __init__(self,name):
self.name=name
self.SubscribersList=[]
def SubscriberAdd(self,subscriber):
self.SubscribersList.append(subscriber)
class Publisher():
def __init__(self,name):
self.name=name
self.SubscribersList=[]
self.NewsList=[]
def NewsListAdd(self,news):
self.NewsList.append(news)
def NewsPublish(self,Subscribers):
for subscriber in Subscribers.SubscribersList:
print("subscriber: {} ".format(subscriber),end=' ')
for news in self.NewsList:
news.printf()
WeiBo=Publisher("hello world")
User=Subscriber("jida")
User.SubscriberAdd("jack")
User.SubscriberAdd("Lucy")
WeiBo.NewsListAdd(News("Mary",'message','string','this is my object'))
WeiBo.NewsPublish(User)