📄 pat4c-1.htm
字号:
<A NAME="auto1044"></A>
<P></P>
<A NAME="auto1045"></A>
<LI>can make your design overly general.
The disadvantage of making it easy to add new components is that it
makes it harder to restrict the components of a composite. Sometimes
you want a composite to have only certain components. With
Composite, you can't rely on the type system to enforce those
constraints for you. You'll have to use run-time checks instead.</LI>
</UL>
<A NAME="implementation"></A>
<H2><A HREF="#samplecode"><IMG SRC="down3-1.gif" tppabs="http://ultra/development/DesignPatterns/lowres/gifsb/down3.gif" BORDER=0 ALT="next:
Sample Code"></A> Implementation</H2>
<A NAME="auto1046"></A>
<P>There are many issues to consider when implementing the Composite
pattern:</P>
<OL>
<A NAME="parentref-def-comp"></A>
<LI><EM>Explicit parent references.</EM>
Maintaining references from child components to their parent can
simplify the traversal and management of a composite structure. The
parent reference simplifies moving up the structure and deleting a
component. Parent references also help support the <A HREF="pat5afs-1.htm" tppabs="http://ultra/development/DesignPatterns/lowres/pat5afs.htm" TARGET="_mainDisplayFrame">Chain of Responsibility (223)</A> pattern.
<A NAME="auto1047"></A>
<P>The usual place to define the parent reference is in the Component
class. Leaf and Composite classes can inherit the reference and the
operations that manage it.</P>
<A NAME="auto1048"></A>
<P>With parent references, it's essential to maintain the invariant that
all children of a composite have as their parent the composite that in
turn has them as children. The easiest way to ensure this is to
change a component's parent <EM>only</EM> when it's being added or
removed from a composite. If this can be implemented once in the Add
and Remove operations of the Composite class, then it can be inherited
by all the subclasses, and the invariant will be maintained
automatically.</P>
</LI>
<A NAME="auto1049"></A>
<P></P>
<A NAME="auto1050"></A>
<LI><EM>Sharing components.</EM>
It's often useful to share components, for example, to reduce storage
requirements. But when a component can have no more than one parent,
sharing components becomes difficult.
<A NAME="flywt-w-compst"></A>
<P>A possible solution is for children to store multiple parents. But
that can lead to ambiguities as a request propagates up the structure.
The
<A HREF="pat4ffs-1.htm" tppabs="http://ultra/development/DesignPatterns/lowres/pat4ffs.htm" TARGET="_mainDisplayFrame">Flyweight (195)</A> pattern shows how to rework a
design to avoid storing parents altogether. It works in cases where
children can avoid sending parent requests by externalizing some or
all of their state.</P>
</LI>
<A NAME="auto1051"></A>
<P></P>
<A NAME="auto1052"></A>
<LI><EM>Maximizing the Component interface.</EM>
One of the goals of the Composite pattern is to make clients unaware
of the specific Leaf or Composite classes they're using. To attain
this goal, the Component class should define as many common operations
for Composite and Leaf classes as possible. The Component class
usually provides default implementations for these operations, and
Leaf and Composite subclasses will override them.
<A NAME="auto1053"></A>
<P>However, this goal will sometimes conflict with the principle of class
hierarchy design that says a class should only define operations that
are meaningful to its subclasses. There are many operations that
Component supports that don't seem to make sense for Leaf classes.
How can Component provide a default implementation for them?</P>
<A NAME="auto1054"></A>
<P>Sometimes a little creativity shows how an operation that would appear
to make sense only for Composites can be implemented for all
Components by moving it to the Component class. For example, the
interface for accessing children is a fundamental part of a Composite
class but not necessarily Leaf classes. But if we view a Leaf as a
Component that <EM>never</EM> has children, then we can define a default
operation for child access in the Component class that never <EM>returns</EM> any children. Leaf classes can use the default
implementation, but Composite classes will reimplement it to return
their children.</P>
<A NAME="auto1055"></A>
<P>The child management operations are more troublesome and are discussed
in the next item.</P>
</LI>
<A NAME="auto1056"></A>
<P></P>
<A NAME="auto1057"></A>
<LI><EM>Declaring the child management operations.</EM>
Although the Composite class <EM>implements</EM> the Add and Remove
operations for managing children, an important issue in the Composite
pattern is which classes <EM>declare</EM> these operations in the
Composite class hierarchy. Should we declare these operations in the
Component and make them meaningful for Leaf classes, or should we
declare and define them only in Composite and its subclasses?
<A NAME="auto1058"></A>
<P>The decision involves a trade-off between safety and transparency:</P>
<UL>
<A NAME="auto1059"></A>
<LI>Defining the child management interface at the root of the class
hierarchy gives you transparency, because you can treat all components
uniformly. It costs you safety, however, because clients may try to
do meaningless things like add and remove objects from leaves.</LI>
<A NAME="auto1060"></A>
<P></P>
<A NAME="auto1061"></A>
<LI>Defining child management in the Composite class gives you safety,
because any attempt to add or remove objects from leaves will be
caught at compile-time in a statically typed language like C++. But
you lose transparency, because leaves and composites have different
interfaces.</LI>
</UL>
<A NAME="auto1062"></A>
<P>We have emphasized transparency over safety in this pattern. If you
opt for safety, then at times you may lose type information and have
to convert a component into a composite. How can you do this without
resorting to a type-unsafe cast?</P>
<A NAME="leaf-in-comp"></A>
<P>One approach is to declare an operation <CODE>Composite*
GetComposite()</CODE> in the Component class. Component provides a default
operation that returns a null pointer. The Composite class redefines
this operation to return itself through the <CODE>this</CODE> pointer:</P>
<A NAME="auto1063"></A>
<PRE>
class Composite;
class Component {
public:
//...
virtual Composite* GetComposite() { return 0; }
};
class Composite : public Component {
public:
void Add(Component*);
// ...
virtual Composite* GetComposite() { return this; }
};
class Leaf : public Component {
// ...
};
</PRE>
<A NAME="auto1064"></A>
<P><CODE>GetComposite</CODE> lets you query a component to see if it's a
composite. You can perform <CODE>Add</CODE> and
<CODE>Remove</CODE> safely on the composite it returns.</P>
<A NAME="auto1065"></A>
<PRE>
Composite* aComposite = new Composite;
Leaf* aLeaf = new Leaf;
Component* aComponent;
Composite* test;
aComponent = aComposite;
if (test = aComponent->GetComposite()) {
test->Add(new Leaf);
}
aComponent = aLeaf;
if (test = aComponent->GetComposite()) {
test->Add(new Leaf); // will not add leaf
}
</PRE>
<A NAME="dynamic_cast"></A>
<P>Similar tests for a Composite can be done using the C++
<CODE>dynamic_cast</CODE> construct.</P>
<A NAME="auto1066"></A>
<P>Of course, the problem here is that we don't treat all components
uniformly. We have to revert to testing for different types before
taking the appropriate action.</P>
<A NAME="auto1067"></A>
<P>The only way to provide transparency is to define default
<CODE>Add</CODE> and <CODE>Remove</CODE> operations in Component. That
creates a new problem: There's no way to implement
<CODE>Component::Add</CODE> without introducing the possibility of it
failing. You could make it do nothing, but that ignores an important
consideration; that is, an attempt to add something to a leaf probably
indicates a bug. In that case, the <CODE>Add</CODE> operation produces
garbage. You could make it delete its argument, but that might not
be what clients expect.</P>
<A NAME="auto1068"></A>
<P>Usually it's better to make <CODE>Add</CODE> and
<CODE>Remove</CODE> fail by default (perhaps by raising an
exception) if the component isn't allowed to have children or if the
argument of <CODE>Remove</CODE> isn't a child of the component,
respectively.</P>
<A NAME="auto1069"></A>
<P>Another alternative is to change the meaning of "remove" slightly. If
the component maintains a parent reference, then we could redefine
<CODE>Component::Remove</CODE> to remove itself from its
parent. However, there still isn't a meaningful interpretation for a
corresponding <CODE>Add</CODE>.</P>
</LI>
<A NAME="auto1070"></A>
<P></P>
<A NAME="auto1071"></A>
<LI><EM>Should Component implement a list of Components?</EM>
You might be tempted to define the set of children as an instance
variable in the Component class where the child access and management
operations are declared. But putting the child pointer in the base
class incurs a space penalty for every leaf, even though a leaf never
has children. This is worthwhile only if there are relatively few
children in the structure.</LI>
<A NAME="auto1072"></A>
<P></P>
<A NAME="auto1073"></A>
<LI><EM>Child ordering.</EM>
Many designs specify an ordering on the children of Composite. In the
earlier Graphics example, ordering may reflect front-to-back ordering.
If Composites represent parse trees, then compound statements can be
instances of a Composite whose children must be ordered to reflect the
program.
<A NAME="auto1074"></A>
<P>When child ordering is an issue, you must design child access
and management interfaces carefully to manage the sequence of
children. The <A HREF="pat5dfs-1.htm" tppabs="http://ultra/development/DesignPatterns/lowres/pat5dfs.htm" TARGET="_mainDisplayFrame">Iterator (257)</A> pattern
can guide you in this.</P>
</LI>
<A NAME="auto1075"></A>
<P></P>
<A NAME="auto1076"></A>
<LI><EM>Caching to improve performance.</EM>
If you need to traverse or search compositions frequently, the
Composite class can cache traversal or search information about its
children. The Composite can cache actual results or just information
that lets it short-circuit the traversal or search. For example, the
Picture class from the Motivation example could cache the bounding box
of its children. During drawing or selection, this cached bounding
box lets the Picture avoid drawing or searching when its children
aren't visible in the current window.
<A NAME="auto1077"></A>
<P>Changes to a component will require invalidating the caches of its
parents. This works best when components know their parents. So if
you're using caching, you need to define an interface for telling
composites that their caches are invalid.</P>
</LI>
<A NAME="auto1078"></A>
<P></P>
<A NAME="auto1079"></A>
<LI><EM>Who should delete components?</EM>
In languages without garbage collection, it's usually best to make a
Composite responsible for deleting its children when it's destroyed.
An exception to this rule is when Leaf objects are immutable and thus
can be shared.</LI>
<A NAME="auto1080"></A>
<P></P>
<A NAME="auto1081"></A>
<LI><EM>What's the best data structure for storing components?</EM>
Composites may use a variety of data structures to store their
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -