首页 > 其他 > 详细

第十九章 组合模式

时间:2016-04-06 23:00:09      阅读:182      评论:0      收藏:0      [点我收藏+]

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

希望用户可以忽略组合对象与单个对象的不同,统一的使用组合结构中的所有对象时,就应该考虑使用组合模式。

//我没写过OA系统,不能理解组合模式。

/**
 * Created by hero on 16-4-6.
 */
public abstract class Component {
    protected String name;

    public abstract void add(Component component);

    public abstract void remove(Component component);

    public abstract void display(int depth);

    public Component(String name) {
        this.name = name;
    }
}
/**
 * Created by hero on 16-4-6.
 */
public class Leaf extends Component {
    @Override
    public void add(Component component) {

    }

    @Override
    public void remove(Component component) {

    }

    @Override
    public void display(int depth) {
        CharUtils.print(‘-‘, depth);
        System.out.println(name);
    }

    public Leaf(String name) {
        super(name);
    }
}
import java.util.LinkedList;
import java.util.List;

/**
 * Created by hero on 16-4-6.
 */
public class Composite extends Component {

    private List<Component> children = new LinkedList<>();

    @Override
    public void add(Component component) {
        children.add(component);
    }

    @Override
    public void remove(Component component) {
        children.remove(component);
    }

    @Override
    public void display(int depth) {
        CharUtils.print(‘-‘, depth);
        System.out.println(name);
        for (Component component : children) {
            component.display(depth + 2);
        }
    }

    public Composite(String name) {
        super(name);
    }
}
/**
 * Created by hero on 16-4-6.
 */
public class CharUtils {
    public static void print(char c, int t) {
        for (int i = 0; i < t; i++)
            System.out.print(c);
    }
}
public class Main {

    public static void main(String[] args) {
        Composite root = new Composite("root");
        root.add(new Leaf("leaf A"));
        root.add(new Leaf("leaf B"));

        Composite comp1 = new Composite("comp1");
        comp1.add(new Leaf("leaf XA"));

        root.add(comp1);

        root.display(1);
    }
}

 

第十九章 组合模式

原文:http://www.cnblogs.com/littlehoom/p/5361300.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!