场景
把部分和整体用树形结构来表示,从而使客户端可以使用统一的方式处理部分对象和整体对象。
核心
- 抽象构件角色:
定义了叶子和容器的共同点 - 叶子构件角色:
无字节点 - 容器构件角色:
有容器特征,可以包含子节点
UML
代码
package com.amberweather.composite;
public interface Component {
void operation();
}
//叶子组件
interface Leaf extends Component{
}
//容器组件
interface Composite extends Component{
void add(Component c);
void remove(Component c);
Component getChild(int index);
}
package com.amberweather.composite;
/**
* 叶子图片的实现
* @author HT
*
*/
public class MyImage implements Leaf{
String name;
public MyImage(String name) {
super();
this.name = name;
}
@Override
public void operation() {
System.out.println("访问到了图片:"+name+"----->并进行了操作");
}
}
package com.amberweather.composite;
/**
* 叶子视屏的实现
* @author HT
*
*/
public class MyVideo implements Leaf{
String name;
public MyVideo(String name) {
super();
this.name = name;
}
@Override
public void operation() {
System.out.println("访问到了视屏:"+name+"----->并进行了操作");
}
}
package com.amberweather.composite;
import java.util.ArrayList;
import java.util.List;
/**
* 父节点容器的实现
* @author HT
*
*/
public class MyFolder implements Composite{
String name;
public MyFolder(String name) {
super();
this.name = name;
}
List<Component> list = new ArrayList();
//注意它的operation会遍历其中的所有子节点
@Override
public void operation() {
System.out.println("访问到了文件夹:"+name+"----->并进行了操作");
for(Component c : list){
c.operation();
}
}
@Override
public void add(Component c) {
list.add(c);
}
@Override
public void remove(Component c) {
list.remove(c);
}
@Override
public Component getChild(int index) {
return list.get(index);
}
}
package com.amberweather.composite;
public class Client {
public static void main(String[] args) {
Composite folder = new MyFolder("D:/");
Component image = new MyImage("自拍");
Component video = new MyVideo("mv");
Composite childeFolder = new MyFolder("学习视屏");
Component childeVideo1 = new MyVideo("数学");
Component childeVideo2 = new MyVideo("语文");
Component childeVideo3 = new MyVideo("英语");
childeFolder.add(childeVideo1);
childeFolder.add(childeVideo2);
childeFolder.add(childeVideo3);
folder.add(image);
folder.add(video);
folder.add(childeFolder);
folder.operation();
}
}