zoukankan      html  css  js  c++  java
  • 合成模式

    合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。合成模式可以使客户端将单纯元素与复合元素同等看待。

    合成模式:安全式和透明式合成模式

     

    1,安全式合成模式


    抽象构件角色:这是一个抽象角色,它给参加组合的对象规定一个接口

    树叶构件角色:代表参加组合的树叶对象,一个树叶没有下级的子对象,定义参加组合的原始对象的行为

    树枝构件角色:代表参加组合的有子对象的对象,并给出树枝构件对象的行为

    1.           package javaPattern.composite;  

    2.             

    3.           import java.util.ArrayList;  

    4.             

    5.             

    6.           interface Component{  

    7.               public void operation();  

    }  

    8.           public class Composite implements Component{  

    9.               private ArrayList<Component> al = new ArrayList<Component>();  

    10.          public void operation() {  

    11.              System.out.println("Composite's operation...");  

    12.                

    13.          }  

      }

    14.          public void add(Component c){  

    15.              al.add(c);  

    16.          }  

    17.          public void remove(Component c){  

    18.              al.remove(c);  

    19.          }  

    20.          public Component getChild(int index){  

    21.              return al.get(index);  

    22.          }  

    23.      }  

    24.      class Leaf implements Component{  

    25.        

    26.          @Override  

    27.          public void operation() {  

    28.              System.out.println("leaf's operation..");  

    29.                

    30.          }  

    31.      }  

    32.      class Client{  

    33.          public static void main(String[] args) {  

    34.              Composite composite = new Composite();  

    35.              Component component1 = new Leaf();  

    36.              Component component2 = new Leaf();  

    37.              composite.add(component1);  

    38.              composite.add(component2);  

    39.          }  

    40.      }  

     

    2,透明式合成模式

    透明式合成模式是在抽象组件角色中声明对对象的操作

  • 相关阅读:
    大小端判断
    引用计数
    STL_ALGORITHM_H
    书单一览
    GIT版本控制系统(二)
    JS随机数生成算法
    STL学习笔记--临时对象的产生与运用
    乱序优化与GCC的bug
    你的灯亮着吗?
    交换机和路由器
  • 原文地址:https://www.cnblogs.com/jinzhengquan/p/1934322.html
Copyright © 2011-2022 走看看