Java結(jié)構(gòu)型模式中的組合模式詳解
一.介紹
組合模式(Composite Pattern)屬于結(jié)構(gòu)型模式。組合模式又叫作部分整體模式,它是一種將對(duì)象組合成樹(shù)狀層次結(jié)構(gòu)的模式,用來(lái)表示整體-部分的關(guān)系,使用戶對(duì)單個(gè)對(duì)象和組合對(duì)象具有一致的訪問(wèn)性。組合模式有透明方式和安全方式兩種實(shí)現(xiàn)方式

二.UML類圖
1.透明方式
- 抽象節(jié)點(diǎn)中定義了規(guī)范,客戶端無(wú)需區(qū)別葉子節(jié)點(diǎn)和樹(shù)枝節(jié)點(diǎn),使用方便
- 葉子節(jié)點(diǎn)本來(lái)無(wú)add、remove、getChild方法,但是因?yàn)槌橄笾卸x了規(guī)范,所以必須實(shí)現(xiàn)它們,會(huì)帶來(lái)一些安全性問(wèn)題

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

三.具體代碼
業(yè)務(wù)代碼
//抽象節(jié)點(diǎn)
public abstract class Component {
abstract void add(Component component);
abstract void remove(Component component);
abstract Component getChild(int i);
abstract void operation();
}
//葉子節(jié)點(diǎn)
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);
}
}
//樹(shù)枝節(jié)點(diǎn)
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();
}
}
四.使用場(chǎng)景
- 需要表示一個(gè)對(duì)象整體與部分的層次結(jié)構(gòu)
- 要求對(duì)用戶隱藏組合對(duì)象與單個(gè)對(duì)象的不同,用戶可以使用統(tǒng)一的接口操作組合結(jié)構(gòu)中的所有對(duì)象
- 組織機(jī)構(gòu)樹(shù)
- 文件/文件夾
五.優(yōu)點(diǎn)
- 簡(jiǎn)化了客戶端代碼(客戶端一致地處理單個(gè)對(duì)象和組合對(duì)象)
- 符合開(kāi)閉原則(新增具體實(shí)現(xiàn)類不需要更改源代碼)
到此這篇關(guān)于Java結(jié)構(gòu)型模式中的組合模式詳解的文章就介紹到這了,更多相關(guān)Java組合模式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatis-Plus如何實(shí)現(xiàn)自動(dòng)加密解密
這篇文章主要介紹了MyBatis-Plus實(shí)現(xiàn)自動(dòng)加密解密方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
Springboot實(shí)現(xiàn)多文件上傳代碼解析
這篇文章主要介紹了Springboot實(shí)現(xiàn)多文件上傳代碼解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
SpringCloud整合Netty集群實(shí)現(xiàn)WebSocket的示例代碼
文章主要介紹了SpringCloud整合Netty集群實(shí)現(xiàn)WebSocket的相關(guān)內(nèi)容,包括服務(wù)注冊(cè)和發(fā)現(xiàn)中心的配置,如使用Nacos、CommandLineRunner啟動(dòng)Netty服務(wù)等,還介紹了通過(guò)Redis實(shí)現(xiàn)消息發(fā)布訂閱的機(jī)制,需要的朋友可以參考下2024-11-11
在Spring中實(shí)現(xiàn)異步處理的步驟和代碼演示
在Spring中實(shí)現(xiàn)異步處理通常涉及到@Async注解,通過(guò)步驟和代碼演示,可以在Spring應(yīng)用程序中實(shí)現(xiàn)異步處理,記住要根據(jù)你的應(yīng)用程序的實(shí)際需求來(lái)調(diào)整線程池和異步方法的設(shè)計(jì),感興趣的朋友跟隨小編一起看看吧2024-06-06

