java 组合对象_Java 中组合模型之对象结构模式的详解
Java 中組合模型之對象結(jié)構(gòu)模式的詳解
一、意圖
將對象組合成樹形結(jié)構(gòu)以表示”部分-整體”的層次結(jié)構(gòu)。Composite使得用戶對單個(gè)對象和組合對象的使用具有一致性。
二、適用性
你想表示對象的部分-整體層次結(jié)構(gòu)
你希望用戶忽略組合對象與單個(gè)對象的不同,用戶將統(tǒng)一使用組合結(jié)構(gòu)中的所有對象。
三、結(jié)構(gòu)
四、代碼
public abstract class Component {
protected String name; //節(jié)點(diǎn)名
public Component(String name){
this.name = name;
}
public abstract void doSomething();
}
public class Composite extends Component {
/**
* 存儲節(jié)點(diǎn)的容器
*/
private List components = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void doSomething() {
System.out.println(name);
if(null!=components){
for(Component c: components){
c.doSomething();
}
}
}
public void addChild(Component child){
components.add(child);
}
public void removeChild(Component child){
components.remove(child);
}
public Component getChildren(int index){
return components.get(index);
}
}
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void doSomething() {
System.out.println(name);
}
}
public class Client {
public static void main(String[] args){
// 構(gòu)造一個(gè)根節(jié)點(diǎn)
Composite root = new Composite("Root");
// 構(gòu)造兩個(gè)枝干節(jié)點(diǎn)
Composite branch1 = new Composite("Branch1");
Composite branch2 = new Composite("Branch2");
// 構(gòu)造兩個(gè)葉子節(jié)點(diǎn)
Leaf leaf1 = new Leaf("Leaf1");
Leaf leaf2 = new Leaf("Leaf2");
branch1.addChild(leaf1);
branch2.addChild(leaf2);
root.addChild(branch1);
root.addChild(branch2);
root.doSomething();
}
}
輸出結(jié)果:
Root
Branch1
Leaf1
Branch2
Leaf2
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
總結(jié)
以上是生活随笔為你收集整理的java 组合对象_Java 中组合模型之对象结构模式的详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 天翼网关-无线光纤猫的设置和有WIFI信
- 下一篇: java美元兑换,(Java实现) 美元