适配器模式

适配器模式是一个结构性的设计模式,允许通过不同的接口为一个类赋予新的用途,这使得使用不同调用方式的系统都能够使用这个类。

也可以让你改变通过客户端类接收到的输入参数以适应被适配者的相关函数。

怎么使用?

另一个使用适配器类的地方是包装器(wrapper),允许你讲一个动作包装成为一个类,然后可以在合适的情形下复用这个类。一个典型的例子是当你为一个table类簇创建一个domain类时,你能够将所有的对应不同表的相同动作封装成为一个适配器类,而不是一个接一个的单独调用这些不同的动作。这不仅使得你能够重用你想要的所有操作,而且当你在不同的地方使用同样的动作时不用重写代码。

比较一下两种实现:

不用适配器的方案

  1. class User(object):  
  2.     def create_or_update(self):  
  3.         pass 
  4.  
  5. class Profile(object):  
  6.     def create_or_update(self):  
  7.         pass 
  8.  
  9. user = User()  
  10. user.create_or_update()  
  11.  
  12. profile = Profile()  
  13. profile.create_or_update() 

如果我们需要在不同的地方做同样的事,或是在不同的项目中重用这段代码,那么我们需要重新敲一遍。

使用包装类的解决方案

看看我们怎么反其道而行:

  1. account_domain = Account()  
  2. account_domain.NewAccount()  

在这种情况下,我们通过一个包装类来实现账户domain类:

  1. class User(object):  
  2.     def create_or_update(self):  
  3.         pass 
  4.  
  5. class Profile(object):  
  6.     def create_or_update(self):  
  7.         pass 
  8.  
  9. class Account():  
  10.     def new_account(self):  
  11.         user = User()  
  12.         user.create_or_update()  
  13.  
  14.         profile = Profile()  
  15.         profile.create_or_update()  

这样的话,你就能够在你需要的时候使用账户domain了,你也可以将其他的类包装到domain类下。

工厂模式

工厂模式是一种创建型的设计模式,作用如其名称:这是一个就像工厂那样生产对象实例的类。

这个模式的主要目的是将可能涉及到很多类的对象创建过程封装到一个单独的方法中。通过给定的上下文输出指定的对象实例。

什么时候使用?

使用工厂模式的最佳时机就是当你需要使用到单个实体的多个变体时。举个例子,你有一个按钮类,这个按钮类有多种变体,例如图片按钮、输入框按钮或是flash按钮等。那么在不同的场合你会需要创建不同的按钮,这时候就可以通过一个工厂来创建不同的按钮。

让我们先来创建三个类:

  1. class Button(object):  
  2.     html = ""  
  3.     def get_html(self):  
  4.         return self.html  
  5.  
  6. class Image(Button):  
  7.     html = "<img alt="" />" 
  8.  
  9. class Input(Button):  
  10.     html = "<input type="text" />" 
  11.  
  12. class Flash(Button):  
  13.     html = ""  

然后创建我们的工厂类:

  1. class ButtonFactory():  
  2.     def create_button(self, typ):  
  3.         targetclass = typ.capitalize()  
  4.         return globals()[targetclass]()  

译注:globals()将以字典的方式返回所有全局变量,因此targetclass = typ.capitalize()将通过传入的typ字符串得到类名(Image、Input或Flash),而globals()[targetclass]将通过类名取到类的类(见元类),而globals()[targetclass]()将创建此类的对象。

我们可以这么使用工厂类:

  1. button_obj = ButtonFactory()  
  2. button = [&#039;image&#039;, &#039;input&#039;, &#039;flash&#039;]  
  3. for b in button:  
  4.     print button_obj.create_button(b).get_html()  

输出将是所有按钮类型的HTML属性。这样骂你就能够根据不同的情况指定不同类型的按钮了,并且很易于重用。


评论关闭