14. 设计模式 组合

组合模式的定义与特点

组合(Composite)模式的定义:有时又叫作部分-整体模式,它是一种将对象组合成树状的层次结构的模式,用来表示“部分-整体”的关系,使用户对单个对象和组合对象具有一致的访问性。

组合模式的主要优点有:

  1. 组合模式使得客户端代码可以一致地处理单个对象和组合对象,无须关心自己处理的是单个对象,还是组合对象,这简化了客户端代码;
  2. 更容易在组合体内加入新的对象,客户端不会因为加入了新的对象而更改源代码,满足“开闭原则”;


其主要缺点是:

  1. 设计较复杂,客户端需要花更多时间理清类之间的层次关系;
  2. 不容易限制容器中的构件;

 

  1. 不容易用继承的方法来增加构件的新功能;

原文链接

http://www.javaxmw.com/info?intId=24

public class CompositeTest {

   public static void main(String[] args) {
          Component c0=new Composite(); 
           Component c1=new Composite(); 
           Component leaf1=new Leaf("1"); 
           Component leaf2=new Leaf("2"); 
           Component leaf3=new Leaf("3");  
           
           c0.add(leaf1); 
           c0.add(c1);
           c1.add(leaf2);
           c1.add(leaf3);  
           
           c0.operation();
   }

}

//抽象构件
interface Component
{
   public void add(Component c);
   public void remove(Component c);
   public void operation();
   public Component getChild(int i);
}

//树叶构件
class Leaf implements Component
{
   private String name;
   public Leaf(String name) {
      this.name = name;
   }
   @Override
   public void add(Component c) {
      
   }

   @Override
   public void remove(Component c) {
      
   }

   @Override
   public void operation() {
       System.out.println("树叶"+name+":被访问!"); 
   }

   @Override
   public Component getChild(int i) {
      return null;
   }
}


//树枝构件
class Composite implements Component
{
   private ArrayList children = new ArrayList();
   @Override
   public void add(Component c) {
      children.add(c);
   }

   @Override
   public void remove(Component c) {
      children.remove(c);
   }

   @Override
   public void operation() {
      for (Object obj:children) {
         ((Component)obj).operation();
      }
      
   }

   @Override
   public Component getChild(int i) {
      return children.get(i);
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值