Bridge模式

 

不要光考虑class之间的继承关系,有时候包含关系也能派上大用场。

 

考虑以下场景,ThreadScheduler类,既要考虑不同的调度方式,还要考虑到不同的操作系统平台。如果按继承关系来设计,如下图,最后派生出来的子类的数目是N1×N2, 其中N1是不同调度方式的数目,N2是不同操作系统平台的数目

 

如果考虑到以下事实,在每个子类里,有一部分逻辑只是和平台相关的,而和具体的调度方式无关。那么这种设计显然的会产生很大的代码重复。自然的,我们可以把平台相关的逻辑单独的拿出来

 

Use the Bridge pattern when:

  • you want run-time binding of the implementation,
  • you have a proliferation of classes resulting from a coupled interface and numerous implementations,
  • you want to share an implementation among multiple objects,
  • you need to map orthogonal class hierarchies.

Consequences include:

  • decoupling the object’s interface,
  • improved extensibility (you can extend (i.e. subclass) the abstraction and implementation hierarchies independently),
  • hiding details from clients.

Bridge is a synonym for the “handle/body” idiom.  This is a design mechanism that encapsulates an implementation class inside of an interface class.  The former is the body, and the latter is the handle.  The handle is viewed by the user as the actual class, but the work is done in the body.“The handle/body class idiom may be used to decompose a complex abstraction into smaller, more manageable classes.  The idiom may reflect the sharing of a single resource by multiple classes that control access to it (e.g. reference counting).”

 

 

一个实际的例子:

 

原文链接:http://sourcemaking.com/design_patterns/bridge

posted @ 2012-02-22 13:50  chengfei164  阅读(224)  评论(0编辑  收藏  举报