代表团模式的目的是什么?

问题描述:

我一直在寻找通过源的SensorManager 在Android和发现,当你注册一个 SensorEventListener 的SensorManager 通行证听者控制到 ListenerDelegate

I was looking through the source to SensorManager in Android and found that when you register a SensorEventListener the SensorManager passes control of the listener to a ListenerDelegate.

我只提这件事作为一个例子。我读会议代表编程*的文章,但我仍然不知道它的目的。为什么会之一,可以使用代理?它是如何帮助一个程序的控制流?什么是使用(或不)之一的缺点是什么?它是最实用的与听众用?

I only bring this up as an example. I read the Wikipedia article on delegate programming but I am still not sure of its purpose. Why would one use a 'delegate'? How does it help the control flow of a program? What are the disadvantages of using (or not) one? Is it most practical for use with listeners?

编辑: ListenerDelegate 上线487和有问题的方法都是围绕行1054

ListenerDelegate is on line 487 and the methods in question are around line 1054.

代表团是不完全在*本书中使用的意义上的设计模式。它是在一些情况下是有用的,并且是对其他模式的基

Delegation is not exactly a 'design pattern' in the sense used in the GoF book. It is useful in a number of scenarios, and is a base for other patterns

  • 当你想之前执行一些其他操作/委派后(这是Decorator模式,但它是基于委托)。例如, Col​​lections.synchronizedList(..)创建一个新的集合,代表原单,但其方法同步。
  • 当你有不兼容的接口,并要适应一个到另一个(Adapter模式)。你得到原来的对象,并从符合所需的接口方法委托给它。例如,有个 EnumerationIterator 类,即适应枚举的迭代接口。这个类有一个规则hasNext()方法,它委托给 enumeration.hasMoreElements()
  • 当你想隐藏一些从你的类的用户复杂性,你可以有授人以不同的实际工作者的方法。例如,可以有的start()的openWindow()刹车(),但是这些方法实际上将委托给发动机,el.windows和制动系统(see也是这个)
  • when you want to perform some additional actions before/after you delegate (that's the Decorator pattern, but it's based on delegation). For example, Collections.synchronizedList(..) creates a new collection that delegates to the original one, but has its methods synchronized.
  • when you have incompatible interfaces and you want to adapt one to the other (the adapter pattern). You get the original object and delegate to it from methods that conform to the desired interface. For example, there's the EnumerationIterator class, that adapts enumerations to the Iterator interface. The class has a hasNext() method which delegates to enumeration.hasMoreElements()
  • when you want to hide some complexity from the user of your class, you can have methods that delegate to different actual workers. For example, a Car can have start(), openWindow() and brake(), but each of these methods will actually delegate to the engine, el.windows and braking system (see also this)