Prototype

Specifies the kinds of objects to create using a prototypical instance and creates new objects by copying (cloning) this prototype. Use it when the classes to instantiate are specified at run-time, to avoid building a parallel factory class hierarchy, or when instances differ only in their initial state and cloning is cheaper than instantiation.

Examples:

  • Like mitotic cell division in biology — the original cell acts as a prototype and produces an identical copy of itself — the pattern delegates cloning to each object via a clone() method, allowing private fields to be copied without exposing them to outside code.
// Each prototype implements Clone()
class Wall {
public:
  virtual Wall* Clone() const { return new Wall(*this); }
};
// Factory stores prototypes and clones on demand
class MazePrototypeFactory {
public:
  MazePrototypeFactory(Wall* w, Room* r, Door* d)
    : _protoWall(w), _protoRoom(r), _protoDoor(d) {}
  Wall* MakeWall() const { return _protoWall->Clone(); }
private:
  Wall* _protoWall; Room* _protoRoom; Door* _protoDoor;
};

Synonyms: clone