image.png
组合模式本质上是构造类似树形结构,一般用在后台管理系统的菜单
第一步,先创建一个抽象类
public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void doSomthing();
}
实现抽象类实例,并且里面放置容器(装载自己实现的抽象父类)
public class Composite extends Component{
public Composite(String name) {
super(name);
}
@Override
public void doSomthing() {
System.err.println("CCCC");
}
protected List<Component> components =new ArrayList<>();
public List<Component> getComponents() {
return components;
}
public void add(Component component){
components.add(component);
}
public void delete(Component component){
components.remove(component);
}
}
客户端验证场景,通过客户端要用到的具体类,再具体实现(Branch,Root,Leaf)其中printNode 是用来打印节点信息
public class Client {
public static void main(String[] args) {
Composite root = new Root("root");
Composite leaf = new Leaf("leaf");
Composite branch1 = new Branch("branch1");
Composite branch2 = new Branch("branch2");
root.add(branch1);
root.add(branch2);
branch1.add(leaf);
printNode(root,0);
}
private static void printNode(Composite component,int depth){
for (int i = 0; i < depth; i++) {
System.err.print("--");
}
System.err.println(component.name);
for (Component entity : component.getComponents()) {
if (entity instanceof Branch) {
printNode(((Composite) entity),depth+1);
}else {
printNode(((Composite) entity),depth+1);
}
}
}
}
具体实现类
public class Root extends Composite{
public Root(String name) {
super(name);
}
@Override
public void doSomthing() {
// System.err.println("Root" + name);
}
@Override
public String toString() {
return "Root{" +
"name='" + name + '\'' +
'}';
}
}
public class Leaf extends Composite{
public Leaf(String name) {
super(name);
}
@Override
public void doSomthing() {
// System.err.println("Leaf_" + name);
}
@Override
public String toString() {
return "Leaf{" +
"name='" + name + '\'' +
'}';
}
}
public class Branch extends Composite{
public Branch(String name) {
super(name);
}
public List<Component> getComponents() {
return components;
}
public void add(Component component){
components.add(component);
}
public void delete(Component component){
components.remove(component);
}
@Override
public void doSomthing() {
// System.err.println("Branch_"+name);
}
@Override
public String toString() {
return "Branch{" +
"name='" + name + '\'' +
'}';
}
}
网友评论