X.d 笔记

小Web,大世界

0%

设计模式(8):组合模式 Composite

将对象组合成树形结构以表示“部分-整体”的层次结构。“组合” 使得用户对单个对象和组合对象的使用具有一致性,对于乘积比较复杂的数据结构使用。

组合模式 composite

问题:

Application needs to manipulate a hierarchical collection of “primitive” and “composite” objects. Processing of a primitive object is handled one way, and processing of a composite object is handled differently. Having to query the “type” of each object before attempting to process it is not desirable.

意图:

  • Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  • Recursive composition
  • “Directories contain entries, each of which could be a directory.”
  • 1-to-many “has a” up the “is a” hierarchy.

例:很少用,所以能想到的场景很少,就拿windows的资源管理器来说,就是一个将文件和文件夹组合在一起的组合模式

代码1:定义需要使用的方法,如ls(window应该叫dir才对^_^),并定义一个文件子类

package com.xdnote.DesignPattern.structural.bridge;

public abstract class Prize {

    private String name = "";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public  abstract boolean validate();

    @Override
    public String toString() {
        return this.name.equals("")?"哎,什么都没中":"恭喜您中得"+this.name;
    }

}

public class File extends Composite{

    private String name;

    public File(String name){
        this.name=name;
    }
    @Override
    public void ls() {
        System.out.println(Client.limit+this.name);
    }
}

代码二:定义文件夹,加入组合方法

package com.xdnote.DesignPattern.structural.composite;

import java.util.ArrayList;
import java.util.List;

public class Dir extends Composite{

    private String name;
    private List<Composite> fileList=new ArrayList<Composite>();
    public void add(Composite o){
        this.fileList.add(o);
    }
    public Dir(String name){
        this.name=name;
    }
    @Override
    public void ls() {
        System.out.println(Client.limit+this.name);
        Client.limit.append("   ");
        if(this.fileList.size()>0){
            for(int i=0;i<this.fileList.size();i++){
                this.fileList.get(i).ls();
            }
        }
        Client.limit.setLength(Client.limit.length()-3);
    }
}

代码三:客户端使用

    public static void main(String[] args) {
        Dir one = new Dir(“文件夹A“), 
                        two = new Dir("文件夹B"),
                        thr = new Dir("文件夹C");
        File 	a = new File("文件A"),
                b = new File("文件B"),
                c = new File("文件C"), 
                d = new File("文件D"), 
                e = new File("文件E");
        one.add(a);
        one.add(two);
        one.add(b);
        two.add(c);
        two.add(d);
        two.add(thr);
        thr.add(e);
        one.ls();

        /**
         * 
         * 
dir111
   a
   dir222
      c
      d
      dir333
         e
   b
   */
    }

小结

组合模式 composite

  • 使用频率:

虽然很简单,但使用非常少,不知道List<Item> 这种算不算呢,哈哈

  • 利弊影响:

用的太少啦,不评价。

  • 小评:

可能做桌面系统开发的会用得多点吧