• 组合模式


    组合模式:将对象组合成树形结构以表示"部分-整体"的层次结构。"Composite使得用户对单个对象和组合对象的使用具有一致性。"

    public abstract class AComponent {

    protected String name;
    public AComponent(String name){
    System.out.println(name);
    }
    abstract public void Add(AComponent c); //添加结点
    abstract public void Remove(AComponent c); //移除结点
    abstract public void Display(int i); //输出结点结构
    }

    //组合类 

    public class Composite extends AComponent{

    static AComponent component;

    private ArrayList children = new ArrayList();

    public Composite(String name) {

    super(name);  }

    public void Add(AComponent c) {

    this.component = c; children.add(c); }

    public void Remove(AComponent c) {

    children.remove(c); }

    public void Display(int i) {

    Iterator iter = children.iterator();

    AComponent c = null;

    c = (AComponent) iter.next();

    while(iter.hasNext()&&iter.next().equals(null))

    { System.out.println("abc------"+c.name); } } }

    //单对象类

    public class Leaf extends AComponent{  

    public Leaf(String name) {

    super(name); }

    public void Add(AComponent c) {

    System.out.println("不能添加子项!"); }

    public void Remove(AComponent c) {

    System.out.println("不能移除子项!"); }

    public void Display(int i) {

    System.out.println("abc"+new String()+name); } }

    //测试类 

    public class Test {

    public static void main(String[] args) {
    Composite root = new Composite("根目录");
    root.Add(new Leaf("---子项A"));
    root.Add(new Leaf("---子项B"));
    Composite comp = new Composite("组合X");
    comp.Add(new Leaf("---子项XA"));
    comp.Add(new Leaf("---子项XB"));
    root.Add(comp);
    root.Add(new Leaf("---子项C"));
    Leaf l = new Leaf("---子项D");
    root.Add(l);
    root.Remove(l);
    root.Display(2);
    }
    }

  • 相关阅读:
    2014.7建兰NOIP模拟Day1 Running
    简单的数论函数模板
    二分图匹配的匈牙利算法
    手算平方根
    ...
    hdu 5396 Expression(区间DP+组合数)
    hdu 5693 D Game(区间DP)
    hdu 5151 Sit sit sit(区间dp+排列组合)
    hdu 4570 Multi-bit Trie(dp)
    hdu 2855 Fibonacci Check-up (矩阵)
  • 原文地址:https://www.cnblogs.com/lee0oo0/p/2511486.html
Copyright © 2020-2023  润新知