Prototype pattern
The Prototype Pattern (Prototype Pattern) is used to create duplicate objects while ensuring performance. This type of design pattern belongs to creational patterns and provides one of the best ways to create objects.
This pattern implements a prototype interface, which is used to create clones of the current object. This pattern is used when the cost of directly creating an object is relatively high. For example, an object needs to be created after an expensive database operation. We can cache the object, return a clone of it on the next request, and update the database when needed, thereby reducing database calls.
Summary
Prototype pattern
Intent: Use a prototype instance to specify the kind of object to be created, and create new objects by copying these prototypes.
Main problem solved: Dynamically establish and delete prototypes at runtime.
When to use it
- The system should be independent of the creation, composition, and representation of products.
- The class to be instantiated needs to be specified at runtime, for example through dynamic loading.
- Avoid creating a factory class hierarchy parallel to the product class hierarchy.
- When a class can have only a few different state combinations, cloning a prototype is more convenient than manual instantiation.
How to solve
Quickly generate instances identical to the prototype object through an existing prototype object.
Key code
- Implement the clone operation:
- In Java, implement the
Cloneableinterface and override theclone()method. - In .NET, use the
ObjectThe class'sMemberwiseClone()method to implement shallow copy, or implement deep copy through serialization.
- Isolates the coupling between the users of class objects and the concrete types, requiring "volatile classes" to have a stable interface.
Application Example
- Cell division
- Java Date Class
Object.clone()Method
Advantages
- Improved performance
- Avoids constraints of constructors
Disadvantages
- Equipping a clone method requires comprehensive consideration of the class's functionality and may be difficult to implement for existing classes, especially when dealing with indirect objects that do not support serialization or references with circular structures.
- must implement the
Cloneableinterface.
Use Cases
- Resource optimization
- Class initialization consumes a lot of resources (such as data and hardware resources)
- Scenarios with high performance and security requirements
- Pass
newWhen creating an object requires complex data preparation or access permissions - An object needs multiple modifiers
- When an object needs to be provided to other objects for access and may be modified by various callers
- Usually used together with the Factory Method pattern, through the
cloneto create the object, then provided to the caller by the factory method
Notes
Unlike creating new objects by directly instantiating a class, the Prototype Pattern generates new objects by copying existing objects. Shallow copy is achieved by implementing the Cloneable interface, and deep copy is achieved by implementing the Serializable and reading a binary stream.
structures
The Prototype Pattern contains the following main roles:
-
Prototype Interface (Prototype Interface): Defines an interface for cloning itself, usually including a
clone()method. -
Concrete Prototype Class (Concrete Prototype): The concrete class that implements the prototype interface, responsible for the actual clone operation. This class needs to implement the
clone()method, usually using shallow copy or deep copy to copy itself. -
Client: Uses prototype instances to create new objects. The client calls the prototype object's
clone()method to create new objects instead of directly using the constructor.
Create a class that implements
We will create an abstract class Shape and entity classes that extend the Shape class. The next step is to define the class ShapeCache, which stores shape objects in a Hashtable and returns their clones when requested.
PrototypePatternDemo Class uses ShapeCache class to get the Shape object.
Step 1
Create an abstract class that implements the Cloneable interface.
Shape.java
public
abstract
class
Shape
implements
Cloneable
{
private
String
id
;
protected
String
type
;
abstract
void
draw
(
)
;
public
String
getType
(
)
{
return
type
;
}
public
String
getId
(
)
{
return
id
;
}
public
void
setId
(
String
id
)
{
this
.
id
=
id
;
}
public
Object
clone
(
)
{
Object
clone
=
null
;
try
{
clone
=
super
.
clone
(
)
;
}
catch
(
CloneNotSupportedException
e
)
{
e
.
printStackTrace
(
)
;
}
return
clone
;
}
}
Step 2
Create the entity classes that extend the above abstract class.
Rectangle.java
public
class
Rectangle
extends
Shape
{
public
Rectangle
(
)
{
type
=
"
Rectangle
"
;
}
@
Override
public
void
draw
(
)
{
System
.
out
.
println
(
"
Inside Rectangle::draw() method.
"
)
;
}
}
Square.java
public
class
Square
extends
Shape
{
public
Square
(
)
{
type
=
"
Square
"
;
}
@
Override
public
void
draw
(
)
{
System
.
out
.
println
(
"
Inside Square::draw() method.
"
)
;
}
}
Circle.java
public
class
Circle
extends
Shape
{
public
Circle
(
)
{
type
=
"
Circle
"
;
}
@
Override
public
void
draw
(
)
{
System
.
out
.
println
(
"
Inside Circle::draw() method.
"
)
;
}
}
Step 3
Create a class that gets entity classes from the database and stores them in a Hashtable it.
ShapeCache.java
import
java
.
util
.
Hashtable
;
public
class
ShapeCache
{
private
static
Hashtable
<
String
,
Shape
shapeMap
=
new
Hashtable
<
String
,
Shape
(
);
public
static
Shape
getShape
(
String
shapeId
)
{
Shape
cachedShape
=
shapeMap
.
get
(
shapeId
)
;
return
(
Shape
)
cachedShape
.
clone
(
)
;
}
//
Run database queries for each shape and create that shape
//
shapeMap.put(shapeKey, shape);
//
For example, we want to add three shapes
public
static
void
loadCache
(
)
{
Circle
circle
=
new
Circle
(
)
;
circle
.
setId
(
"
1
"
)
;
shapeMap
.
put
(
circle
.
getId
(
)
,
circle
)
;
Square
square
=
new
Square
(
)
;
square
.
setId
(
"
2
"
)
;
shapeMap
.
put
(
square
.
getId
(
)
,
square
)
;
Rectangle
rectangle
=
new
Rectangle
(
)
;
rectangle
.
setId
(
"
3
"
)
;
shapeMap
.
put
(
rectangle
.
getId
(
)
,
rectangle
)
;
}
}
Step 4
PrototypePatternDemo Use ShapeCache class to get the shapes stored in the Hashtable clones of the
PrototypePatternDemo.java
public
class
PrototypePatternDemo
{
public
static
void
main
(
String
[
]
args
)
{
ShapeCache
.
loadCache
(
)
;
Shape
clonedShape
=
(
Shape
)
ShapeCache
.
getShape
(
"
1
"
)
;
System
.
out
.
println
(
"
Shape :
"
clonedShape
.
getType
(
)
)
;
Shape
clonedShape2
=
(
Shape
)
ShapeCache
.
getShape
(
"
2
"
)
;
System
.
out
.
println
(
"
Shape :
"
clonedShape2
.
getType
(
)
)
;
Shape
clonedShape3
=
(
Shape
)
ShapeCache
.
getShape
(
"
3
"
)
;
System
.
out
.
println
(
"
Shape :
"
clonedShape3
.
getType
(
)
)
;
}
}
Step 5
Run the program, output result:
Shape : Circle
Shape : Square
Shape : Rectangle