What is the purpose of a delegation pattern?
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 theIterator
interface. The class has ahasNext()
method which delegates toenumeration.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 havestart()
,openWindow()
andbrake()
, but each of these methods will actually delegate to the engine, el.windows and braking system (see also this)
As per effective Java (by Joshua Bloch), composition is favorable over inheritance. Composition has several advantages over inheritance. One of the intuitions for this is as follows: Consider a sub-class which inherits from a base class. So any change in the base class will make the sub-class fragile as the sub-class depends on the base class. By using inheritance, we are making a binding on the sub-class to depend on the base class, which makes our code fragile. However by using composition, we can remove this limitation. Composition is done by establishing a 'has-a relationship' between classes instead of 'is-a' relationship as in inheritance. 'Delegate pattern' and 'Decorator pattern' both are examples of how composition can be achieved. You might want to read the chapter on 'composition vs inheritance' in the effective java book as it is quite informative.
For shorter explanation, you can refer to this article: http://javarevisited.blogspot.com/2013/06/why-favor-composition-over-inheritance-java-oops-design.html
The delegate pattern is used to have someone else actually do the work, so, for example, in your example the SensorManager
isn't going to know how to do what every listener wants, but you only want one program listening to the sensor.
So, there are listeners created by calling registerListener
on the SensorManager
, and these listeners are passed the information and then can decide what to do with the data from the sensors.