Usefall
The Prototype Pattern
Purpose
A complex thing exists.
I want to create a thing just like it, but with slight modifications.
Writer Tiger
I finished writing my first book yesterday!
class Protobook {
constructor(introduction, chapter1, chapter2, conclusion) {
this.introduction = introduction;
this.chapter1 = chapter1;
this.chapter2 = chapter2;
this.conclusion = conclusion;
}
}
tigersFirstBook = new Protobook(
"There was once a great tiger.",
"The tiger went on an adventure.",
"He made lots of friends on his journey.",
"The tiger fought a dragon and saved the world."
);
Writer Tiger
I want to make another version of the book that’s just like it,
But with a different ending.
Rewriting the book from scratch is hard to do!
Protobook
So in other words you want to use me as a prototype
to make more books?
Writer Tiger
Woah! You can talk!?
Yes, how can I do that?
Protobook
I am a special kind of book, a Protobook.
I can be used as a prototype,
because I have a
clone()
method.Just call
clone()
and leave the rest to me!
class Protobook {
constructor(introduction, chapter1, chapter2, conclusion) {
this.introduction = introduction;
this.chapter1 = chapter1;
this.chapter2 = chapter2;
this.conclusion = conclusion;
}
clone() {
return new Protobook(
this.introduction,
this.chapter1,
this.chapter2,
this.conclusion
);
}
}
tigersFirstBook = new Protobook(
"There was once a great tiger.",
"The tiger went on an adventure.",
"He made lots of friends on his journey.",
"The tiger fought a dragon and saved the world."
);
let tigersSecondBook = tigersFirstBook.clone();
tigersSecondBook.conclusion = "The tiger befriended the dragon.";
Writer Tiger
That was easy! You are so cool Protobook!
You took care of all the cloning stuff!
Protobook
I know I am cool. Thank me more.
Solution
Use the complex thing as a prototype to create the other thing you wanted.
Other code can simply call the clone function of the prototype to create a copy and then make any further modifications.