Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
107 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

  • 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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...