设计模式==组合模式(Composite)

/*
 *
 * 组合模式(Composite)
 *
 *
 * 把整体和局部的关系用树状结构描述出来,使得客户端把整体对象和局部对象同等看待。
 */

package model;

import java.util.*;

public class TestComposite {
    public static void main(String[] args) {
        Node n1 = new LeafNode(3);
        Node n2 = new LeafNode(4);
        Node n3 = new LeafNode(6);
        Node n4 = new LeafNode(5);
        Node n5 = new LeafNode(2);
        Node n6 = new LeafNode(9);
        Node n7 = new LeafNode(12);
        Node n8 = new LeafNode(7);
        Node n9 = new LeafNode(8);
        Node c1 = new CompositeNode(n1, n2, n3);
        Node c4 = new CompositeNode(n8, n9);
        Node c3 = new CompositeNode(n5, c4);
        Node c2 = new CompositeNode(n4, c3);
        Node c5 = new CompositeNode(n6, n7);
        Node root = new CompositeNode(c1, c2, c5);
        System.out.println(root.getValue());
    }
}

abstract class Node {
    public abstract int getValue();
}

class LeafNode extends Node {
    int value;

    public LeafNode(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

class CompositeNode extends Node {
    private List<Node> children = new ArrayList<Node>();

    public CompositeNode(Node... nodes) {
        for (Node n : nodes) {
            children.add(n);
        }
    }

    public int getValue() {
        int result = 0;
        for (Node n : children) {
            result += n.getValue();
        }
        return result;
    }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值