The intent of the prototype pattern is to provide new objects by copying examples. A major difference caused by copying is that a copy typically includes some of the state of the original object.
The Prototype pattern is used when creating an instance of a class is very time-consuming or complex in some way. Then, rather than creating more instances, you make copies of the original instance, modifying them as appropriate. Prototypes can also be used whenever you need classes that differ only in the type of processing (or field) they offer i.e. when there are many subclasses that differ only in the kind of objects they create a Prototype Pattern can be used to reduce the number of subclasses by cloning a prototype.
see UML:

some explaination:
- Prototype (ColorPrototype)
- declares an interface for cloning itself
- ConcretePrototype (Color)
- implements an operation for cloning itself
- Client (ColorManager)
- creates a new object by asking a prototype to clone itself
When to copy, Object.clone() can help. But the clone() is not deep copy, that's should be noticed.
本文详细介绍了原型模式的概念及其应用场景。该模式通过复制实例而非创建新对象来节省时间和资源,适用于实例创建过程复杂的情况。文章还解释了如何实现原型模式,并提到了深拷贝与浅拷贝的区别。
657

被折叠的 条评论
为什么被折叠?



