80 likes | 251 Views
Composition , Aggregation, and Delegation. COMP 401 Spring 2014 Lecture 11 2/ 20/2014. Layers of Abstraction. Simple objects Object state (i.e., fields) are basic data types As objects become more complex…
E N D
Composition, Aggregation, and Delegation COMP 401 Spring 2014 Lecture 11 2/20/2014
Layers of Abstraction • Simple objects • Object state (i.e., fields) are basic data types • As objects become more complex… • Encapsulated object state is complex enough to require additional “layers of abstraction”. • Object state is modeled by a combination of other objects. • Recall earliest examples with Triangle and Point • Lecture4, ta.v09 and ta.v10
Composition and Aggregation • Two design techniques for creating an object that encapsulates other objects. • Whole / part relationship • Any specific situation is not necessarily strictly one or the other. • In a nutshull… • Composition • The individual parts that make up the whole are “owned” solely by the whole. • They don’t otherwise have a reason for being. • Aggregation • The individual parts that make up the whole may also exist on their own outside of the whole. • Or even as a partof other objects.
Example of Aggregation • lec11.ex1 • Course • Models a course at the university • Encapsulates Room, Professor, and a list of Student objects
Characteristics of Aggregation • Encapsulated objects provided externally • As parameters to constructor • Getters and setters for these components often provided. • Encapsulated objects may be independently referenced outside of the aggregating object • Including possibly as part of another aggregation.
Example of Composition • lec11.ex2 • Car • Two implementations: HondaOdyssey and Porche911 • Both encapsulate an implementation of Horn and an implementation of Engine • Implementations of Engine written with inheritance. • EngineImpl provides most of the implementation • Abstract class • ManualEngine and AutomaticEngineare subclasses • Override setGear()
Characteristics of Composition • Encapsulated objects created internally • Usually within the constructor • No setters and often no getters • Encapsulated objects do not make sense outside of the abstraction. • Not shared with other abstractions • Functionality / state of encapsulated objects only accessible through the abstraction
Delegation • Claiming an “is-a” relationship with an interface but relying on another object to actually do the work. • Can occur with either aggregation or composition. • Although more common with composition • Composition example revisited • lec11.ex3 • Both Car implementations also now claim Horn and/or AdjustableHorn interfaces as well. • Actual work of these interfaces delegated to internal horn object.