最近学了下组合设计模式,很有心得,于是看了一些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
类型的列表,所以Container
和Component
可以组成一个树结构;Container
继承自component
,树状结构中节点和叶子的共有行为 updateGraphicsData
被先定义在Component
中,Container
里面实现对所有的 都进行update 操作。
上面类名 | 对应下图 |
---|---|
Container | Composite |
Component | Component |
叶子(未出现) | Leaf |
标准组合设计模式,如下图: