写给Python初学者的设计模式入门(1)(2)
适配器模式
适配器模式是一个结构性的设计模式,允许通过不同的接口为一个类赋予新的用途,这使得使用不同调用方式的系统都能够使用这个类。
也可以让你改变通过客户端类接收到的输入参数以适应被适配者的相关函数。
怎么使用?
另一个使用适配器类的地方是包装器(wrapper),允许你讲一个动作包装成为一个类,然后可以在合适的情形下复用这个类。一个典型的例子是当你为一个table类簇创建一个domain类时,你能够将所有的对应不同表的相同动作封装成为一个适配器类,而不是一个接一个的单独调用这些不同的动作。这不仅使得你能够重用你想要的所有操作,而且当你在不同的地方使用同样的动作时不用重写代码。
比较一下两种实现:
不用适配器的方案
- class User(object):
- def create_or_update(self):
- pass
- class Profile(object):
- def create_or_update(self):
- pass
- user = User()
- user.create_or_update()
- profile = Profile()
- profile.create_or_update()
如果我们需要在不同的地方做同样的事,或是在不同的项目中重用这段代码,那么我们需要重新敲一遍。
使用包装类的解决方案
看看我们怎么反其道而行:
- account_domain = Account()
- account_domain.NewAccount()
在这种情况下,我们通过一个包装类来实现账户domain类:
- class User(object):
- def create_or_update(self):
- pass
- class Profile(object):
- def create_or_update(self):
- pass
- class Account():
- def new_account(self):
- user = User()
- user.create_or_update()
- profile = Profile()
- profile.create_or_update()
这样的话,你就能够在你需要的时候使用账户domain了,你也可以将其他的类包装到domain类下。
工厂模式
工厂模式是一种创建型的设计模式,作用如其名称:这是一个就像工厂那样生产对象实例的类。
这个模式的主要目的是将可能涉及到很多类的对象创建过程封装到一个单独的方法中。通过给定的上下文输出指定的对象实例。
什么时候使用?
使用工厂模式的最佳时机就是当你需要使用到单个实体的多个变体时。举个例子,你有一个按钮类,这个按钮类有多种变体,例如图片按钮、输入框按钮或是flash按钮等。那么在不同的场合你会需要创建不同的按钮,这时候就可以通过一个工厂来创建不同的按钮。
让我们先来创建三个类:
- class Button(object):
- html = ""
- def get_html(self):
- return self.html
- class Image(Button):
- html = "<img alt="" />"
- class Input(Button):
- html = "<input type="text" />"
- class Flash(Button):
- html = ""
然后创建我们的工厂类:
- class ButtonFactory():
- def create_button(self, typ):
- targetclass = typ.capitalize()
- return globals()[targetclass]()
译注:globals()将以字典的方式返回所有全局变量,因此targetclass = typ.capitalize()将通过传入的typ字符串得到类名(Image、Input或Flash),而globals()[targetclass]将通过类名取到类的类(见元类),而globals()[targetclass]()将创建此类的对象。
我们可以这么使用工厂类:
- button_obj = ButtonFactory()
- button = ['image', 'input', 'flash']
- for b in button:
- print button_obj.create_button(b).get_html()
输出将是所有按钮类型的HTML属性。这样骂你就能够根据不同的情况指定不同类型的按钮了,并且很易于重用。
评论关闭