Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4999505
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2013-05-21 14:51:34

看了twisted core document 里面的Tutorials 第4小节,如何把代码写成component based 的结构,使用了components模块里面的registerAdaper(). 
以及Hight level twisted 的Components: Interfaces and Adapters 小节,介绍adapter: Objects which implement an interface for another object type are called adapters.

一个简单的例子可以说明registerAdapter的作用:


  1. class IB(interface):
  2.     def some_op():

  3. class A:
  4.     def do_something(self):

  5. class B:
  6.     implements(IB)

  7. class AdaptAToB:
  8.     implements(IB)

  9.     def __init__(self, original):
  10.         self._original = original

  11.     def some_op(self):
  12.         self._original.do_something()

  13. #将AdaptAToB 登记为 A 作为B 使用的时候的转换器。
  14. components.registerAdapter(AdaptAToB, A, B)

  15. a = A()
  16. b = B()

IB(a): an instance of AdaptAToB.
IB(b): an instance of B.

adapter 的好处是可以 将多个classes 组织成离散的块。比如,如果要多加一个class C,C有需要作为B使用,那么只需要增加class AdaptCToB; 更加简单的情况,如果A和B 都implement 同一个interface,这个interface有个方法是do_something(), 那么只需要一个Adaper class 就可以。这样子,新增一个新的class 变得很简单。
阅读(1020) | 评论(0) | 转发(0) |
0

上一篇:python glob模块

下一篇:twisted 学习笔记

给主人留下些什么吧!~~