Design Patterns Design Patterns
Design Patterns Design Patterns
Composite Pattern
Structural Pattern
Now, we can create separate interfaces for individual objects and collection of objects. However we want to
be able to treat the collection of objects and individual objects in the th same way yet still have the ability to distinguish between them
Composite pattern describes how to use recursive composition so that clients don't have to make this distinction
Design Patterns 4
Composite Pattern p
Structure
Design Patterns
Composite: Example p p
Now, if the company is successful, each of these company members receives a salary, and we could at any time ask y, y for the cost of any employee to the company.
We define the cost as the salary of that person and those of all his subordinates:
The cost of an individual employee is simply his salary (and benefits). The cost of an employee who heads a department is his salary plus those of all his subordinates.
We would like a single interface that will produce the y y p y salary totals correctly whether the employee has subordinates or not.
public float getSalaries();
Design Patterns
Design Patterns
Design Patterns
Implementation issues p
References to parent class
The parent maintains a list of its children If a child component also k hild t l knows about it parent, it can simplify the traversal and b t its t i lif th t l d management of composite structures
Go for Transparency !
Design Patterns 10
Implementation Issues p
Child Ordering
Depends on the type of the composite object
In a Graphics application
ordering may reflect front-to-back ordering
Design child access and management interfaces carefully to manage the sequence of children
The Iterator pattern can be helpful in this regard
Caching Results
If you frequently ask for data which must be computed from a series of child components, it may be advantageous to cache these i f hild t b d t t h th computed results in the parent However, unless the computation is relatively intensive and you are quite certain that the underlying data have not changed, this may not be worth the effort
Design Patterns 11
makes the client simple makes it easier to add new kinds of components.
as long as they support the same programming interface
Cons
can make your design overly general
disadvantage of making it easy to add new components is that it p p makes it harder to restrict the components of a composite sometimes you want a composite to have only certain components
Design Patterns 12