Java面试经验第一季之设计模式——组合模式

组合模式的定:“将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。”

Java面试经验第一季之设计模式——组合模式

组合模式

角色:

1.Component 是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component

子部件。

2.Leaf 在组合中表示叶子结点对象,叶子结点没有子结点。

3.Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除

(remove)等。

说的简单点,两个子类继承了一个抽象类,抽象类包含抽象方法,一个子类为叶子节点,实现了抽象类的抽象方法,另一个子类组合了叶子节点,实现了对叶子节点对象的操作。

Component 类

扫描二维码关注公众号,回复: 5305988 查看本文章

abstract class Component {

protected String name;

public Component(String name) {

this.name = name;

}

public abstract void Add(Component c);

public abstract void Remove(Component c);

public abstract void Display(int depth);

}

Leaf 类

class Leaf extends Component {

public Leaf(String name) {

super(name);

}

@Override

public void Add(Component c) {

System.out.println("Can not add to a leaf");

}

@Override

public void Remove(Component c) {

System.out.println("Can not remove from a leaf");

}

@Override

public void Display(int depth) {

String temp = "";

for (int i = 0; i < depth; i++)

temp += '-';

System.out.println(temp + name);

}

}

Composite 类

class Composite extends Component {

private List<Component> children = new ArrayList<Component>();

public Composite(String name) {

super(name);

}

@Override

public void Add(Component c) {

children.add(c);

}

@Override

public void Remove(Component c) {

children.remove(c);

}

@Override

public void Display(int depth) {

String temp = "";

for (int i = 0; i < depth; i++)

temp += '-';

System.out.println(temp + name);

for (Component c : children) {

c.Display(depth + 2);

}

}

}

应用场景


常用于表示树形结构中,例如二叉树,数等。

文件系统:文件系统由目录和文件组成。每个目录都可以装内容。目录的内容可以是文件,也 可以是目录。

按照这种方式,计算机的文件系统就是以递归结构来组织的。如果你想要描述这样的数据结构,那么你可以使用组合模式。

猜你喜欢

转载自blog.csdn.net/qq_41552245/article/details/87867544