Pattern · Core

Prototype

Create new objects by CLONING an existing, fully-configured instance — instead of building from scratch with `new`.

Asked atAmazonGoogleAdobe
step 1 / 7
1/2Clone, don't rebuild
«interface»
Shape
+ clone(): Shape
Circle
- radius
- color
+ clone()
Rectangle
- w, h
+ clone()
Clone, don't rebuild
1interface Shape {
2 Shape clone(); // every shape can copy itself
3}
4class Circle implements Shape {
5 int radius; Color color;
6 public Shape clone() {
7 return new Circle(radius, color); // same field values
8 }
9}
State
contractclone(): Shape

Shape declares one method: clone(). Every shape promises it can produce a copy of itself.