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

最近学了下组合设计模式,很有心得,于是看了一些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 操作。

上面类名对应下图
ContainerComposite
ComponentComponent
叶子(未出现)Leaf

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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值