Design Patterns GOF23 combination mode

Combined mode Composite

Scene combination mode : the relationship between parts and the whole is represented by a tree structure, so that the client may use a unified and integral processing target objects (files and folders)

Core combined mode :

                             - abstract component (Component) role: defines the common ground leaves and container

                             - leaf (Leaf) component role: no child nodes

                             - the container (Composite) component role: container wherein: a child node may comprise, or other container

Such as anti-virus software:

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 new Folder ( "Favorites");
   Folder F5 = new new Folder ( "my novel");
   F2 = new ImageFile ( "Zhang");
   F3 = the TextFile new new ( "Wulin");
   F4 = the TextFile new new ( "Families with children");
   f5.add (F3);
   f5.add (F4);
   f1.add ( F2);
   f1.add (F5);
   f1.killVirus ();
  }
}

Guess you like

Origin www.cnblogs.com/code-fun/p/11334569.html