I was looking through the source to SensorManager in Android and found that when you register a SensorEventListener
the SensorManager
passes contro
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.
in a very simple sentence I can say: the main purpose of Delegation is to shields your objects from implementation changes to other objects in your software. read more here
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
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
Collections.synchronizedList(..)
creates a new collection that delegates to the original one, but has its methods synchronized.EnumerationIterator
class, that adapts enumerations to the Iterator
interface. The class has a hasNext()
method which delegates to enumeration.hasMoreElements()
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)