Java設計模式之組合模式

[color=red]COMPOSITE[/color] (Object Structural)
[color=red]Purpose[/color]
Facilitates the creation of object hierarchies where each object
can be treated independently or as a set of nested objects
through the same interface.
[color=red]Use When[/color]
1 Hierarchical representations of objects are needed..
2 Objects and compositions of objects should be treated uniformly.
[color=red]Example[/color]
Sometimes the information displayed in a shopping cart is the
product of a single item while other times it is an aggregation
of multiple items. By implementing items as composites we can
treat the aggregates and the items in the same way, allowing us
to simply iterate over the tree and invoke functionality on each
item. By calling the getCost() method on any given node we
would get the cost of that item plus the cost of all child items,
allowing items to be uniformly treated whether they were single
items or groups of items.

package javaPattern.composite;

import java.util.ArrayList;


interface Component{
public void operation();
}
public class Composite implements Component{
private ArrayList<Component> al = new ArrayList<Component>();
@Override
public void operation() {
System.out.println("Composite's operation...");

}
public void add(Component c){
al.add(c);
}
public void remove(Component c){
al.remove(c);
}
public Component getChild(int index){
return al.get(index);
}
}
class Leaf implements Component{

@Override
public void operation() {
System.out.println("leaf's operation..");

}

}
class Client{
public static void main(String[] args) {
Composite composite = new Composite();
Component component1 = new Leaf();
Component component2 = new Leaf();
composite.add(component1);
composite.add(component2);
}
}
發佈了40 篇原創文章 · 獲贊 0 · 訪問量 837
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章