现在的位置: 首页 > 综合 > 正文

Design Patterns — Prototype

2013年07月15日 ⁄ 综合 ⁄ 共 906字 ⁄ 字号 评论关闭

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.

     

     

  • 抱歉!评论已关闭.