Java結構型模式中的組合模式詳解
更新時間:2023年02月16日 16:18:35 作者:非凡的小笨魚
組合模式,又叫部分整體模式,它創(chuàng)建了對象組的數(shù)據(jù)結構組合模式使得用戶對單個對象和組合對象的訪問具有一致性。本文將通過示例為大家詳細介紹一下組合模式,需要的可以參考一下
一.介紹
組合模式(Composite Pattern)屬于結構型模式。組合模式又叫作部分整體模式,它是一種將對象組合成樹狀層次結構的模式,用來表示整體-部分的關系,使用戶對單個對象和組合對象具有一致的訪問性。組合模式有透明方式和安全方式兩種實現(xiàn)方式

二.UML類圖
1.透明方式
- 抽象節(jié)點中定義了規(guī)范,客戶端無需區(qū)別葉子節(jié)點和樹枝節(jié)點,使用方便
- 葉子節(jié)點本來無add、remove、getChild方法,但是因為抽象中定義了規(guī)范,所以必須實現(xiàn)它們,會帶來一些安全性問題

2.安全方式
- 客戶端需要區(qū)別葉子節(jié)點和樹枝節(jié)點,使用不方便
- 葉子節(jié)點無add、remove、getChild方法,不存在安全性問題

三.具體代碼
業(yè)務代碼
//抽象節(jié)點
public abstract class Component {
abstract void add(Component component);
abstract void remove(Component component);
abstract Component getChild(int i);
abstract void operation();
}
//葉子節(jié)點
class Leaf extends Component{
private String name;
public Leaf(String name) {
this.name = name;
}
@Override
void add(Component component) {}
@Override
void remove(Component component) {}
@Override
Component getChild(int i) {
return null;
}
@Override
void operation() {
System.out.print(name);
}
}
//樹枝節(jié)點
class Composite extends Component{
private ArrayList<Component> children = new ArrayList<>();
@Override
void add(Component component) {
children.add(component);
}
@Override
void remove(Component component) {
children.remove(component);
}
@Override
Component getChild(int i) {
return children.get(i);
}
@Override
void operation() {
children.forEach(Component::operation);
}
}客戶端
public class Client {
public static void main(String[] args) {
Component level1 = new Composite();
level1.add(new Leaf("1"));
level1.add(new Leaf("2"));
Component level2 = new Composite();
level2.add(new Leaf("2.1"));
level1.add(level2);
level1.operation();
}
}
四.使用場景
- 需要表示一個對象整體與部分的層次結構
- 要求對用戶隱藏組合對象與單個對象的不同,用戶可以使用統(tǒng)一的接口操作組合結構中的所有對象
- 組織機構樹
- 文件/文件夾
五.優(yōu)點
- 簡化了客戶端代碼(客戶端一致地處理單個對象和組合對象)
- 符合開閉原則(新增具體實現(xiàn)類不需要更改源代碼)
到此這篇關于Java結構型模式中的組合模式詳解的文章就介紹到這了,更多相關Java組合模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringCloud整合Netty集群實現(xiàn)WebSocket的示例代碼
文章主要介紹了SpringCloud整合Netty集群實現(xiàn)WebSocket的相關內(nèi)容,包括服務注冊和發(fā)現(xiàn)中心的配置,如使用Nacos、CommandLineRunner啟動Netty服務等,還介紹了通過Redis實現(xiàn)消息發(fā)布訂閱的機制,需要的朋友可以參考下2024-11-11

