设计模式:合成方式

设计模式:合成模式

原文地址:http://leihuang.org/2014/12/09/composite/


Structural 模式 如何设计物件之间的静态结构,如何完成物件之间的继承、实 现与依赖关系,这关乎着系统设计出来是否健壮(robust):像是易懂、易维护、易修改、耦合度低等等议题。Structural 模式正如其名,其分类下的模式给出了在不同场合下所适用的各种物件关系结构。

  • Default Adapter 模式
  • Adapter 模式
  • Bridge 模式
  • Composite 模式
  • Decorator 模式
  • Facade 模式
  • Flyweight 模式
  • Proxy 模式

Composite模式是构造型的设计模式之一,通过递归手段来构造诸如文件系统之类的树形的对象结构;Composite模式所代表的数据构造是一群具有统一接口界面的对象集合,并可以通过一个对象来访问所有的对象(遍历)。

举个例子,比如一棵树包括树枝和树叶,树枝上面又有树枝和树叶,这样一直循环下去...如下图

设计模式:合成方式

假如让你实现一棵树,你会不会把每一个树枝都给定义出来?肯定不会.那么这就需要用到组合模式.组合模式基本结构如下图.

设计模式:合成方式

我们现在就利用组合模式来实现,这棵树.

设计模式:合成方式

IBranch 接口

public interface IBranch {
    public void print() ;
}

Leaf 类

public class Leaf implements IBranch {

    private String leaf = null ;

    public Leaf(String leaf){
        this.leaf = leaf ;
    }

    @Override
    public void print() {
        System.out.println(leaf);
    }
}

BranchComposite 类

import java.util.LinkedList;
import java.util.List;

public class BranchComposite implements IBranch {

    private List<IBranch> branchList = null ;

    public BranchComposite(){
        branchList = new LinkedList<IBranch>() ;
    }

    public void add(IBranch branch){
        branchList.add(branch) ;
    }

    public boolean remove(IBranch branch){
        return branchList.remove(branch) ;
    }

    @Override
    public void print() {
        for(IBranch branch : branchList){
            branch.print();
        }
    }
}

Client 类

public class Client {
    public static void main(String[] args) {
        IBranch leaf1 = new Leaf("leaf 1") ;
        IBranch leaf2 = new Leaf("leaf 2") ;
        IBranch leaf3 = new Leaf("leaf 3") ;

        BranchComposite branch0 = new BranchComposite() ;
        BranchComposite branch1 = new BranchComposite() ;
        BranchComposite branch2 = new BranchComposite() ;

        branch0.add(leaf1);
        branch0.add(branch1);

        branch1.add(leaf2);
        branch1.add(branch2);

        branch2.add(leaf3);

        //branch0.print() ;
        //branch1.print() ;
        //branch2.print() ;
    }
}

2014-12-09 17:09:18

Brave,Happy,Thanksgiving !