zoukankan      html  css  js  c++  java
  • 浅谈设计模式--组合模式(Composite Pattern)

    组合模式(Composite Pattern)

    组合模式,有时候又叫部分-整体结构(part-whole hierarchy),使得用户对单个对象和对一组对象的使用具有一致性。简单来说,就是可以像使用一个对象那样,来使用一组对象(The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object.),最后达到用户和这一组对象的解耦。请看下图:

    Component,就是对Leaf和Composite的抽象,是Leaf和Composite必须实现的接口(或者抽象类)

    这单个对象,就是Composite,提供操作Leaf的方法和实现所用Component的方法。

    这一组对象,就是Leaf。

    例子如下:

    /** Component **/
    interface Graphic {
    
        //Prints the graphic
        public void print();
        
    }
    
    
    /** Leaf **/
    public class CircleLeaf implements Graphic {
    
        public void print() {
          System.out.println("Circle...");
        }
    
    }
    
    
    /** Leaf **/
    public class RectangleLeaf implements Graphic{
    
        public void print() {
          System.out.println("Rectangle...");
        }
    }
    /** Composite **/
    public class GraphicComposite implements Graphic{
    
        private List<Graphic> childGraphics = new ArrayList<Graphic>();
    
        public void print() {
          //key method. Loop and call Leaf method.
          for(Graphic g : childGraphics){
              g.print();
          }
        }
        
        // manipulate Leaf
        public void add(Graphic g){
          childGraphics.add(g);
        }
        public void remove(Graphic g){
          childGraphics.remove(g);
        }
       
    }

    这样,客户端就不需要操作每一个Leaf,直接通过GraphicComposite可以操作所有的Leaf:

    public class ClientSide {
       
        public static void main(String[] args) {
        
        GraphicComposite graphic = new GraphicComposite();
        graphic.add(new CircleLeaf());
        graphic.add(new RectangleLeaf());
        
        graphic.print();
        }
    }

    最后,最开始看到的这个模式的使用,是在我参加的一个开源项目里。当时候觉得设计得不错,没想到是Composite模式。之后,自己也在项目中使用过,特此写下此贴来总结一下。

    参考:

    http://en.wikipedia.org/wiki/Composite_pattern

    http://www.cnblogs.com/peida/archive/2008/09/09/1284686.html

  • 相关阅读:
    php 显示文件 与Windows文件名排序一致
    pip3 install uwsgi 报错
    centos7 安装mysql 5.7
    Win7 开始菜单搜索添加快捷方式
    centos7.7 clamav 查杀病毒
    CentOS7.x 默认php版本与php7.4共存
    centos6.5 yum安装redis
    centos6 yum安装mysql 5.6 (完整版)
    解决phpmyadmin出现: Maximum execution time of 300
    Castle Windsor 使MVC Controller能够使用依赖注入
  • 原文地址:https://www.cnblogs.com/techyc/p/3531452.html
Copyright © 2011-2022 走看看