vimwiki/tech/prototype.wiki

27 lines
950 B
Plaintext
Raw Normal View History

2022-03-16 02:30:01 +00:00
= 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.
2022-03-16 02:45:01 +00:00
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