Iterator
Definition-Provide a way to access the elements of an aggregate object equentially without exposing its underlying representation.
Composite Pattern
Definition-Compose objects into tree structures to represent part-whole hierarchies.Composite lets clients treat individual objects and compositions of objects uniformly. This is called recursive composition.
//UML Picture
Use the Composite pattern when
- You want to represent part-whole hierarchies of objects
- You want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly.
Benefits
-It makes it easy to add new kinds of components
-It makes clients simpler, since they do not have to know if they are dealing with a leaf or a composite component
Liabilities
It makes it harder to restrict the type of components of a composite
//Example
//code
//Graphic.java
import java.util.ArrayList;
import java.util.Iterator;
public abstract class Graphic ... {
public void Draw()
...{
throw new UnsupportedOperationException();
}
public void Add(Graphic g)
...{
throw new UnsupportedOperationException();
}
public void Remove(Graphic g)
...{
throw new UnsupportedOperationException();
}
public Graphic GetChild(int i)
...{
throw new UnsupportedOperationException();
}
}
class GraphicElement extends Graphic
... {
String Name;
public GraphicElement(String Name)
...{
this.Name = Name;
}
public void Draw()
...{
System.out.println(Name);
}
}
class CompositeElement extends Graphic
... {
String Name;
ArrayList elements;
public CompositeElement(String Name)
...{
this.Name = Name;
elements = new ArrayList();
}
public void Add(Graphic g)
...{
elements.add(g);
}
public void Remove(Graphic g)
...{
elements.remove(g);
}
public Graphic GetChild(int i)
...{
if(i<elements.size() && elements.get(i)!=null)
return (Graphic)elements.get(i);
else
return null;
}
public void Draw()
...{
System.out.println(Name);
Iterator iterator=elements.iterator();
while(iterator.hasNext())
...{
Graphic g=(Graphic)iterator.next();
g.Draw();
}
}
}
//Main.java
public class Main ... {
public static void main(String[] args) ...{
GraphicElement aText=new GraphicElement("aText");
GraphicElement aLine1=new GraphicElement("aLine");
GraphicElement aLine2=new GraphicElement("aLine");
GraphicElement aRectangle1=new GraphicElement("aRectangle");
GraphicElement aRectangle2=new GraphicElement("aRectangle");
CompositeElement aPicture1=new CompositeElement("aPicture1");
CompositeElement aPicture2=new CompositeElement("aPicture2");
aPicture2.Add(aText);
aPicture2.Add(aLine1);
aPicture2.Add(aRectangle1);
aPicture1.Add(aPicture2);
aPicture1.Add(aLine2);
aPicture1.Add(aRectangle2);
aPicture1.Draw();
}
}
//results
//if u have anything interesting, pls contact with me.QQ:95491590