zoukankan      html  css  js  c++  java
  • 设计模式之GOF23组合模式

    组合模式Composite

    使用组合模式的场景:把部分和整体的关系用树形结构表示,从而使客户端可以使用统一的方式处理对象和整体对象(文件和文件夹)

    组合模式核心

                                 -抽象构件(Component)角色:定义了叶子和容器的共同点

                                 -叶子(Leaf)构件角色:无子节点

                                 -容器(Composite)构件角色:有容器特征:可以包含子节点或者其他容器

    例如杀毒软件:

    public abstract class  File {
         protected String name;
      abstract void killVirus();//杀毒
      public File(String name) {
       this.name = name;
      }
      
    }
    class ImageFile extends  File{
     public ImageFile(String name) {
      super(name);
     }
     public void killVirus() {
      System.out.println("对图片"+this.name+".jpg进行杀毒");
     }
    }
    class TextFile extends  File{
     public TextFile(String name) {
      super(name);
     }
     public void killVirus() {
      System.out.println("对文本"+this.name+".txt进行杀毒");
     }
    }
    class Folder extends File{
     List<File> files;
     public Folder(String name) {
      super(name);
      files=new ArrayList<File>();
     }
     public void add(File f) {
      files.add(f);
     }
     public void remove(int index) {
      files.remove(index);
     }
     public File getChild(int index) {
      return files.get(index);
     }
     void killVirus() {
      System.out.println("对"+this.name+"进行查杀");
      for(File f:files) {//天然的递归
       f.killVirus();
      }
     }
    }

    public class Client {
      public static void main(String[] args) {
       File f2,f3,f4;
       Folder f1=new Folder("我的收藏");
       Folder f5=new Folder("我的小说");
       f2=new ImageFile("小张");
       f3=new TextFile("武林外传");
       f4=new TextFile("家有儿女");
       f5.add(f3);
       f5.add(f4);
       f1.add(f2);
       f1.add(f5);
       f1.killVirus();
      }
    }

  • 相关阅读:
    1-13Object类之toString方法
    jvm源码解读--16 锁_开头
    jvm源码解读--16 cas 用法解析
    jvm源码解读--15 oop对象详解
    jvm源码解读--14 defNewGeneration.cpp gc标记复制之后,进行空间清理
    jvm源码解读--13 gc_root中的栈中oop的mark 和copy 过程分析
    Error: Could not find or load main class ***
    使用javah 给.class类编译jni_helloworld.h文件头
    jvm源码解读--12 invokspecial指令的解读
    jvm源码解读--11 ldc指令的解读
  • 原文地址:https://www.cnblogs.com/code-fun/p/11334569.html
Copyright © 2011-2022 走看看