Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (179.65 KB, 6 trang )
<span class='text_page_counter'>(1)</span><div class='page_container' data-page=1>
<b>CSIE Department, NTUT</b>
<b>Woei-Kae Chen</b>
<b>AbstractClass *p, *p1; // client</b>
<b>...</b>
<b>p1 = new AbstractClass; // error</b>
<b>...</b>
<b>p1 = new ConcreteClass; // ok. but...</b>
<b>...</b>
<b>Tool</b>
Manipulate()
<b>GraphicTool</b>
Manipulate()
<b>WholeNote</b>
Draw()
<b>HalfNote</b>
Draw()
Clone() Clone()
return copy of self return copy of self
prototype
p=prototype->Clone()
while (user drags mouse) {
p->Draw(new position)
}
insert p into drawing
<b>Graphic</b>
Draw()
Clone()
<b>Staff</b>
Draw()
Clone()
<b>MusiclNote</b>
<b>Client</b>
– when the classes to instantiate are specified at
run-time.
– to avoid building a class hierarchy of factories
that parallelsthe class hierarchy of products.
<b>ConcretePrototype2</b>
<b>Client</b>
Operation()
<b>Prototype</b>
Clone()
<b>ConcretePrototype1</b>
Clone() Clone()
prototype
p=prototype->Clone()
return copy of self return copy of self
– declares an interface for cloning itself
– implements an operation for cloning itself
<b>AbstractClass *p, *p1; // client</b>
<b>...</b>
<b>...</b>
<b>...</b>
<b>p1 = p->Clone(); // prototype</b>
zHidesthe concrete product classes from the clientỈ
reducing the number of names clients know about.
– Adding and removing products at run-time
zadd a new concrete class into a system by simply registering a
prototypical instance.
– Specifying new objects by varying values
zvary the values of an object’s variables and clone
– Specifying new objects by varying structure
zcloning a subcircuit (composed as a Composite Pattern)
– may be difficult when the internals of a concrete
subclass include objects that does not support
copying
– may be difficult when the internals of a concrete
subclass includes objects that have circular
references
z<b>Using a prototype manager</b>
– client keeps a registry of available prototypes
zthe number of prototypes need not be fixed
zenables clients to extend without writing code
z<b>Implementing the <sub>Clone</sub>operation</b>
– shallowcopy versus deepcopy
zdo the clone and the original share variables?
zC++ default copy constructor does a member-wise
copy Ỉpointers will be shared between the copy
and the original
z<b>Initializing clones</b>
– no parameter for the <b>Clone</b>operation
(uniform interface)
zreset states after clone
zintroduce an <b>Initialize</b>operation
Original
Ptr
Object
Ptr
Object
deep copy
<b>class AbstractClass {</b>
<b>public:</b>
<b>virtual AbstractClass *Clone() const;</b>
<b>...</b>
<b>};</b>
<b>class ConcreteClass {</b>
<b>public:</b>
<b>AbstractClass *Clone() const {</b>
<b>return new ConcreteClass(*this);</b>
<b>}</b>
<b>...</b>
<b>};</b>
<b>Copy Constructor</b> <b>Shallow copy?</b>
<b>Deep copy?</b>