• 合成模式


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

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

     

    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,透明式合成模式

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

  • 相关阅读:
    题解 BZOJ1026 & luogu P2657 [SCOI2009]windy数 数位DP
    BZOJ 1867 [Noi1999]钉子和小球 DP
    P5057 [CQOI2006]简单题 前缀异或差分/树状数组
    P2051 [AHOI2009]中国象棋 大力DP
    P4208 [JSOI2008]最小生成树计数
    BZOJ 2440 [中山市选2011]完全平方数 二分+容斥
    Luogu P1951 收费站_NOI导刊2009提高(2) 二分 最短路
    Luogu P3527 [POI2011]MET-Meteors 整体二分
    Luogu P4109 [HEOI2015]定价 贪心
    Luogu P2114_[NOI2014]起床困难综合症 贪心
  • 原文地址:https://www.cnblogs.com/jinzhengquan/p/1934322.html
Copyright © 2020-2023  润新知