我在一个销售产品的网站上工作(一类销售,一类产品)。每当我销售产品时,我都想将该操作保存在历史表中,并且我决定使用观察者模式来执行此操作。
即:我的类Sales是主题,History类是观察者,每当我调用Sales类的save_sale()方法时,我都会通知观察者。 (我决定使用这种模式,因为稍后我还会发送电子邮件、通知管理员等)
这是我的主题类(Sales 类由此扩展)
class Subject:
_observers = []
def attach(self, observer):
if not observer in self._observers:
self._observers.append(observer)
def detach(self, observer):
try:
self._observers.remove(observer)
except ValueError:
pass
def notify(self,**kargs):
for observer in self._observers:
observer.update(self,**kargs)
在 View 中我做了这样的事情
sale = Sale()
sale.user = request.user
sale.product = product
h = History() #here I create the observer
sale.attach(h) #here I add the observer to the subject class
sale.save_sale() #inside this class I will call the notify() method
这是History的更新方法
def update(self,subject,**kargs):
self.action = "sale"
self.username = subject.user.username
self.total = subject.product.total
self.save(force_insert=True)
它第一次运行良好,但是当我尝试进行另一次销售时,我收到一条错误消息,指出由于主键约束,我无法插入历史记录。
我的猜测是,当我第二次调用 View 时,第一个观察者仍在 Subject 类中,现在我有两个历史观察者正在监听 Sales,但我不确定是否是这个问题(天哪我想念来自 php 的 print_r)。
我做错了什么?我什么时候必须“附加”观察者?或者有更好的方法吗?
顺便说一句:我使用的是 Django 1.1,但我无权安装任何插件。
最佳答案
这可能不是一个可接受的答案,因为它与体系结构更相关,但是您是否考虑过使用信号来通知系统更改?看来您正在尝试执行信号的设计目的。 Django 信号与观察者模式具有相同的最终结果功能。
关于python - 在 Django 中使用观察者模式的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3676517/