java.awt.container源码中的组合设计模式

北城余情 提交于 2019-12-29 21:36:49

最近学了下组合设计模式,很有心得,于是看了一些java中的用到组合设计的源码。再此分享给大家。

java.awt.container #add(component) 是使用的组合设计模式。下面上两个类的代码。

public abstract class Component implements ImageObserver, MenuContainer,
                                           Serializable
{
boolean updateGraphicsData(GraphicsConfiguration gc) {
    checkTreeLock();

    if (graphicsConfig == gc) {
        return false;
    }

    graphicsConfig = gc;

    ComponentPeer peer = getPeer();
    if (peer != null) {
        return peer.updateGraphicsData(gc);
    }
    return false;
}...
}
public class Container extends Component {

    /**
     * The components in this container.
     * @see #add
     * @see #getComponents
     */
    private java.util.List<Component> component = new ArrayList<>();
    @Override
    boolean updateGraphicsData(GraphicsConfiguration gc) {
    checkTreeLock();

    boolean ret = super.updateGraphicsData(gc);

    for (Component comp : component) {
        if (comp != null) {
            ret |= comp.updateGraphicsData(gc);
        }
    }
    return ret;
}
...
}

因为Container里面有一个component类型的列表,所以ContainerComponent 可以组成一个树结构;Container 继承自component ,树状结构中节点和叶子的共有行为 updateGraphicsData被先定义在Component 中,Container里面实现对所有的 都进行update 操作。

上面类名 对应下图
Container Composite
Component Component
叶子(未出现) Leaf

标准组合设计模式,如下图:
在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!