组合模式(Composite Pattern)

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

角色:
1. Component 是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component子部件
2. Leaf 在组合中表示叶子结点对象,叶子结点没有子结点
3. Composite 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关操作,如增加(add)和删除(remove)等

代码如下:
Componnent类

package src2;

public class Component {
    protected String name;

    public Component(String name) {
        super();
        this.name = name;
    }

    public void Add(Component c) {

    }

    public void Remove(Component c) {

    }

    public void Display(int depth){

    }
}

Leaf类

package src2;

public class Leaf extends Component{

    public Leaf(String name) {
        super(name);
        // TODO Auto-generated constructor stub
    }

    public void Add(Component c) {
        System.out.println("没有此功能");
    }

    public void Remove(Component c){
        System.out.println("没有此功能");
    }

    public void  Display(int depth) {
        System.out.println("-"+depth + name);
    }
}

Composite类

package src2;
import java.util.*;


public class Composite extends Component{
    private List<Component> list = new ArrayList<Component>();

    public Composite(String name) {
        super(name);
        // TODO Auto-generated constructor stub
    }

    public void Add(Component c) {
        list.add(c);
    }

    public void Remove(Component c){
        list.remove(c);
    }

    public void Display(int depth){
        System.out.println("-" + depth + name);
        for (Component item : list) {
            item.Display(depth + 2);
        }
    }
}

客户端代码

package src2;

public class t1 {
    public static void main(String[] args) {

        Composite root = new Composite("root");
        root.Add(new Leaf("Leaf A"));
        root.Add(new Leaf("Leaf B"));

        Composite comppComposite = new Composite("compX");
        comppComposite.Add(new Leaf("Leaf XA"));
        comppComposite.Add(new Leaf("Leaf XB"));
        root.Add(comppComposite);

        Composite comp2 = new Composite("compY");
        comp2.Add(new Leaf("Leaf XYA"));
        comp2.Add(new Leaf("Leaf XYB"));
        comppComposite.Add(comp2);

        root.Add(new Leaf("Leaf C"));
        Leaf leaf = new Leaf("Leaf D");
        root.Add(leaf);
        root.Remove(leaf);

        root.Display(1);

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值