---
title: "组合模式"
author: "rainyear"
date: "2012-10-23T10:07:55Z"
tags: []
categories: ["非技术"]
slug: "untitled"
draft: false
lastmod: "2012-10-23T10:07:55Z"
id: 1703137
url: "https://rainyear.iteye.com/blog/1703137"
---

**组合模式将对象以树形结构组织起来，以达成“部分－整体”的层次结构，使得客户端对单个对象和组合对象的使用具有一致性。**

 

水果类，相当于Component

package compositedemo;

import java.util.ArrayList;

import java.util.List;

public abstract class Fruit {

protected List&lt;Fruit&gt; children;

public Fruit() {

this.children = new ArrayList&lt;Fruit&gt;();

}

public void add(Fruit fruit) throws UnsupportedOperationException {

throw new UnsupportedOperationException("叶子节点不应调用此方法");

}

public void remove(Fruit fruit) throws UnsupportedOperationException {

throw new UnsupportedOperationException("叶子节点不应调用此方法");

}

public abstract void get();

}

\---------------------

苹果类，相当于Composite

package compositedemo;

public class Apple extends Fruit {

@Override

public void add(Fruit fruit) {

// TODO Auto-generated method stub

this.children.add(fruit);

}

@Override

public void remove(Fruit fruit) {

// TODO Auto-generated method stub

this.children.remove(fruit);

}

@Override

public void get() {

// TODO Auto-generated method stub

for (Fruit child : this.children) {

child.get();

}

}

}

\-----------------------

香蕉类，相当于Composite

package compositedemo;

public class Banana extends Fruit {

@Override

public void add(Fruit fruit) {

// TODO Auto-generated method stub

this.children.add(fruit);

}

@Override

public void remove(Fruit fruit) {

// TODO Auto-generated method stub

this.children.remove(fruit);

}

@Override

public void get() {

// TODO Auto-generated method stub

for (Fruit child : this.children) {

child.get();

}

}

}

\-----------------------

北方苹果类，相当于Leaf，其他具体水果类似

package compositedemo;

public class NorthApple extends Fruit {

@Override

public void get() {

// TODO Auto-generated method stub

System.out.println("NorthApple get");

}

}

\-----------------------

测试类，相当于Client

package compositedemo;

public class Client {

public static void main(String\[] args) {

 

Fruit apple=new Apple();

Fruit banana=new Banana();

 

Fruit northApple = new NorthApple();

Fruit northBanana = new NorthBanana();

Fruit southApple = new SouthApple();

Fruit southBanana = new SouthBanana();

apple.add(northApple);

// apple.add(southApple);

// banana.add(northBanana);

banana.add(southBanana);

 

System.out.println("组合对象调用功能方法");

apple.get();

banana.get();

 

System.out.println("叶子对象调用功能方法");

northApple.get();

northBanana.get();

southApple.get();

southBanana.get();

}

}

[![](http://a.hiphotos.baidu.com/zhidao/wh%3D450%2C600/sign=f9c5c67d6e061d957d133f3c4ec426e7/dcc451da81cb39dbe639d813d0160924aa1830fd.jpg)](http://a.hiphotos.baidu.com/zhidao/pic/item/dcc451da81cb39dbe639d813d0160924aa1830fd.jpg "点击查看大图")