Explaination Merged
Explaination Merged
1. Introduction –
I was listening to Car Talk, a popular weekly broadcast during which callers ask questions about their
vehicles. Before every program break, the show's hosts ask callers to dial 1-800-CAR-TALK, which
corresponds to 1-800-227-8255. Of course, the former proves much easier to remember than the latter, in
part because the words "CAR TALK" are a composite: two words that represent seven digits.
Humans generally find it easier to deal with composites, rather than their individual components.
Likewise, when you develop object-oriented software, it's often convenient to manipulate composites just
like you manipulate individual components. That premise represents the fundamental principle of the
Composite design pattern.
2. The Pattern
Composite objects: objects that contain other objects; for example, a drawing may be composed of
graphic primitives, such as lines, circles, rectangles, text, and so on.
Developers need the Composite pattern because we often must manipulate composites exactly the same
way we manipulate primitive objects. For example, graphic primitives such as lines or text must be
drawn, moved, and resized. But we also want to perform the same operation on composites, such as
drawings, that are composed of those primitives. Ideally, we'd like to perform operations on both
primitive objects and composites in exactly the same manner, without distinguishing between the two. If
we must distinguish between primitive objects and composites to perform the same operations on those
two types of objects, our code would become more complex and more difficult to implement, maintain,
and extend.
Implementing the Composite pattern is easy. Composite classes extend a base class that represents
primitive objects.
Figure-1
For every method implemented in the Component class, the Composite class implements a method
with the same signature that iterates over the composite's components, as illustrated by the draw()
method listed above.
The Composite class extends the Component class, so you can pass a composite to a method that
expects a component; for example, consider the following method:
The preceding method is passed a component either a simple component or a composite then it invokes
that component's draw() method. Because the Composite class extends Component, the
repaint()method need not distinguish between components and composites it simply invokes the
draw() method for the component (or composite).
Figure 1's Composite pattern class diagram illustrate one problem with the pattern: you must distinguish
between components and composites when you reference a Component, and you must invoke a
composite specific method, such as addComponent(). You typically fulfill that requirement by
adding a method, such as isComposite(), to the Component class. That method returns false for
components and is overridden in the Composite class to return true. Additionally, you must also cast
the Component reference to a Composite instance, like this:
Notice that the addComponent() method is passed a Component reference, which can be either a
primitive component or a composite.
Figure-2
If you implement Figure 2's Composite pattern, you don't ever have to distinguish between components
and composites, and you don't have to cast a Component reference to a Composite instance. So the code
fragment listed above reduces to a single line:
...
component.addComponent(someComponentThatCouldBeAComposite);
...
But, if the Component reference in the preceding code fragment does not refer to a Composite, what
should the addComponent() do? That's a major point of contention with Figure 2's Composite pattern
implementation. Because primitive components do not contain other components, adding a component to
another component makes no sense, so the Component.addComponent() method can either fail
silently or throw an exception. Typically, adding a component to another primitive component is
considered an error, so throwing an exception is perhaps the best course of action.
package com.cakes;
String name;
float price;
Here is the Menu class. It has a list of menu items of type Item. Items can be added via the
addItem() method. The iterator() method returns an iterator of menu items. The MenuIterator
class is an inner class of Menu that implements the Iterator interface for Item objects. It
contains basic implementations of the hasNext(), next(), and remove() methods.
Menu.java
package com.cakes;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
List<Item> menuItems;
public Menu() {
menuItems = new ArrayList<Item>();
}
@Override
public boolean hasNext() {
if (currentIndex >= menuItems.size()) {
return false;
} else {
return true;
}
}
@Override
public Item next() {
return menuItems.get(currentIndex++);
}
@Override
public void remove() {
menuItems.remove(--currentIndex);
}
The Demo class demonstrates the iterator pattern. It creates three items and adds them to the
menu object. Next, it gets an Item iterator from the menu object and iterates over the items in
the menu. After this, it calls remove() to remove the last item obtained by the iterator.
Following this, it gets a new iterator object from the menu and once again iterates over the
menu items.
Demo.java
package com.cakes;
import java.util.Iterator;
System.out.println("Displaying Menu:");
Iterator<Item> iterator = menu.iterator();
while (iterator.hasNext()) {
Item item = iterator.next();
System.out.println(item);
}
System.out.println("\nDisplaying Menu:");
iterator = menu.iterator();
while (iterator.hasNext()) {
Item item = iterator.next();
System.out.println(item);
}
Displaying Menu:
spaghetti: $7.5
hamburger: $6.0
chicken sandwich: $6.5
Displaying Menu:
spaghetti: $7.5
hamburger: $6.0
Note that since the menu utilizes a Java collection, we could have used an iterator obtained
for the menu list rather than write our own iterator as an inner class.
CASE STUDY – INTERNET BASED WEATHER MONITORING STATION
The weather station is based on WeatherData object, which tracks current weather conditions
(temperature, humidity, and barometric pressure). We have to create an application that initially
provides three display elements:
Current conditions
Weather statistics
Simple forecast
All these display elements are updated in real-time as the WeatherData object acquires the most
recent measurements.
This is an expandable weather station. We need to release an API so that other developers can write
their own weather displays and plug them right in.
APPLICATION OVERVIEW
The three players in the system are the weather station (the physical device that acquire actual
weather data), the WeatherData object (that tracks the data coming from the Weather Station and
updates the displays), and the display that shows the users the current weather conditions.
OUR JOB
Create an application that uses the WeatherData object to update three displays for current
conditions, weather stats, and forecast.
DISPLAY ELEMENTS
FIRST IMPLEMENTATION
//instance variables
public void measurementChanged(){
}
} By coding to concrete implementations we have
no way to add or remove other display elements
without making changes to the program
To get the class instance, the singleton class can provide a method for example a getInstance() method, this will
be the only method that can be accessed to get the instance.
private Service() { }
return instance;
}
There are some rules that need to be followed when we want to implement a singleton.