zoukankan      html  css  js  c++  java
  • 组合模式-虚有其表的模式

    组合模式:

    1.作用:

    把多个对象组成树状结构来表示局部与整体,这样用户可以一样的对待单个对象和对象的组合。

    2.例子

    /** "Component" */
    interface Graphic {
     
        //Prints the graphic.
        public void print();
    }
     
    /** "Composite" */
    import java.util.List;
    import java.util.ArrayList;
    class CompositeGraphic implements Graphic {
     
        //Collection of child graphics.
        private List<Graphic> childGraphics = new ArrayList<Graphic>();
     
        //Prints the graphic.
        public void print() {
            for (Graphic graphic : childGraphics) {
                graphic.print();
            }
        }
     
        //Adds the graphic to the composition.
        public void add(Graphic graphic) {
            childGraphics.add(graphic);
        }
     
        //Removes the graphic from the composition.
        public void remove(Graphic graphic) {
            childGraphics.remove(graphic);
        }
    }
     
    /** "Leaf" */
    class Ellipse implements Graphic {
     
        //Prints the graphic.
        public void print() {
            System.out.println("Ellipse");
        }
    }
     
    /** Client */
    public class Program {
     
        public static void main(String[] args) {
            //Initialize four ellipses
            Ellipse ellipse1 = new Ellipse();
            Ellipse ellipse2 = new Ellipse();
            Ellipse ellipse3 = new Ellipse();
            Ellipse ellipse4 = new Ellipse();
     
            //Initialize three composite graphics
            CompositeGraphic graphic = new CompositeGraphic();
            CompositeGraphic graphic1 = new CompositeGraphic();
            CompositeGraphic graphic2 = new CompositeGraphic();
     
            //Composes the graphics
            graphic1.add(ellipse1);
            graphic1.add(ellipse2);
            graphic1.add(ellipse3);
     
            graphic2.add(ellipse4);
     
            graphic.add(graphic1);
            graphic.add(graphic2);
     
            //Prints the complete graphic (four times the string "Ellipse").
            graphic.print();
        }
    }

    这个模式太简单了,它有确定的用途,将不同的对象有统一操作方式,不管是符合对象,还是单一对象。

    我想它更多的场景特点。太过于虚有其表,以至于从来没有把它放在心上,不会有专门人在这种场景下,定义类名为composite。

  • 相关阅读:
    Vue 环境配置
    Vue-think脚手架
    搭建vue环境网站
    数组 还是 字符串
    javascript jquery console调试方法说明
    获取 stoken 或者id MVC写法
    它山之石
    Android学习笔记_44_apk安装、反编译及防治反编译
    (转)超级实用且不花哨的js代码大全
    Android学习笔记_43_网络通信之文件断点上传
  • 原文地址:https://www.cnblogs.com/tom-zhao/p/4418302.html
Copyright © 2011-2022 走看看