前言
刚刚看了EuroPython 2017一篇演讲,Why You Don’t Need Design Patterns in Python,为什么python不用设计模式。演讲者是STXNEXT的Sebastian Buczynski。
他对设计模式的定义是:
- 常见问题的通用可复用解决方案
- 定型的最佳实践
他说设计模式是一种似曾相识(Anology),是一种大纲(Outline),他认为设计模式并不是拿来就能用的。
Singleton
第一个是Singleton模式,Singleton的精髓就是任何时候,只有一个类的实例。
《设计模式》里面给出的Singleton代码是
声明:
class Singleton { public: static Singleton* Instance(); protected: Singleton(); private: static Singleton* _instance; };
实现:
Singleton* Singleton::_instance = 0;
Sebastian 在 Google 上面找Singleton的Python实现,找到了以下代码:
声明:
class Singleton: _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance
实现:
one_instance = Singleton() another_instance = Singleton() one_instance is another_instance # True
Sebastian指出,照抄C++,当然也可以解决问题,但是在python里面有更好的解决方案。比如,可以用@classmethod。不过,最好的解决方案是直接用module。因为module本身就是唯一的,相当于module就实现了singleton,那么,我们为什么要大费周章,搞一个singleton出来呢?
我回忆了一下,尽管Singleton是最简单的设计模式了,但是,我这么多年一直没用。以前写C#的时候,我用的是静态类,静态类本身就是唯一的,所以我不需要singleton。当然,我看到有人也用C#写了和C++一样的Singleton,但是我觉得解决问题就可以了,没必要为了写设计模式而写设计模式。同样,写VB.net的时候,我直接用的module,也不需要singleton。
结论:当年《设计模式》里面的Singleton模式,是为了只有一个类实例。如果编程语言本身,如python, c#, vb.net,已经提供了这样的能力,就没有必要再用C++的套路了。或者说,设计模式就不需要了。
Facade
Command
Command模式把请求封装成对象。
Sebastian认为,在python里面,函数就是一等公民,所以没有必要创建对象。
def command(discount_rate): some<strong style="color:transparent">本文来源gao@daima#com搞(%代@#码@网&</strong>_obj.notify_users_about_discount()
也可以用functools创建command
import functools command = functools.partial( some_obj.notify_users_about_discount, discount_rate=0.5 ) command() # equals to some_obj.notify_users_about_discount(discount_rate=0.5)