vimwiki/tech/prototype.wiki

27 lines
950 B
Plaintext

= Prototype =
This is a design pattern where we copy an existing object without making the
code dependent on their classes.
The general idea is sometimes we need an exact clone of an object. We cant copy
the object exactly from the outside, as we dont know the private fields.
Therefore, the object can implement a `clone` method to return an exact copy of
the object. Such an object that implements `clone` is a *prototype*
== Prototype registry ==
Some objects are commonly copied, and therefore we can cache them in a
[[hash_table]] for O(1) lookup, then just call `clone` on the object and return
the new object.
== Implementation ==
Often it only needs to be a method, `clone()` which returns the same type as
`this`, and just calls `return myObject(this)`.
== Use case ==
* when code shouldnt depend on the concrete classes of objects that you need to
copy
* Reduce number of subclasses that differ in how their init their subobjects