组合模式
介绍
组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。
代码演示
package com.cyc.design.composite;
import java.util.ArrayList;
import java.util.List;
/**
* 组合模式
*/
abstract class Node {
abstract public void p();
}
/**
* 叶节点
*/
class LeafNode extends Node {
String content;
public LeafNode(String content) {
this.content = content;
}
@Override
public void p() {
System.out.println(content);
}
}
/**
* 枝节点
*/
class BranchNode extends Node {
//枝节点中不仅包含自己 , 还可以包含页节点
List<Node> nodes = new ArrayList<>();
String name;
public BranchNode(String name) {
this.name = name;
}
@Override
public void p() {
System.out.println(name);
}
/**
* 这里将子节点加载进去
* @param node
*/
public void add(Node node) {
nodes.add(node);
}
}
public class Main {
public static void main(String[] args) {
BranchNode root = new BranchNode("root");
//新建两个枝节点
BranchNode chapter1 = new BranchNode("chapter1");
BranchNode chapter2 = new BranchNode("chapter2");
//新建两个页节点
Node r1 = new LeafNode("r1");
Node c11 = new LeafNode("c11");
Node c12 = new LeafNode("c12");
//新建一个枝节点,属于枝节点chapter2的子节点
BranchNode b21 = new BranchNode("section21");
Node c211 = new LeafNode("c211");
Node c212 = new LeafNode("c212");
root.add(chapter1);
root.add(chapter2);
root.add(r1);
chapter1.add(c11);
chapter1.add(c12);
chapter2.add(b21);
b21.add(c211);
b21.add(c212);
//调用tree
tree(root, 0);
}
static void tree(Node b, int depth) {
for (int i = 0; i < depth; i++) {
System.out.print("--");
}
b.p();
if (b instanceof BranchNode) {
for (Node node : ((BranchNode) b).nodes) {
//这里进行递归调用, 打印树装结构
tree(node, depth + 1);
}
}
}
}