Prototype Pattern
[tr] Türkçe Oku 2023-06-11
Once upon a time, there was a place called the Land of Creators. In this land, there was a secret to creating new objects quickly and efficiently. This secret was called the “Prototype Pattern”.
One day in the Land of Creators, there was a magical drawing pen. This pen had the ability to copy any object it touched. This feature made the creation of objects easy and fast, because instead of creating each object from scratch, an existing object was being copied.
This story is implemented in the C# language as follows:
public interface IPrototype
{
IPrototype Clone();
}
public class ConcretePrototype : IPrototype
{
public IPrototype Clone()
{
return (IPrototype)this.MemberwiseClone(); // Shallow copy
}
}
The same story in Java:
public interface Prototype {
Prototype clone();
}
public class ConcretePrototype implements Prototype {
public Prototype clone() {
try {
return (ConcretePrototype) super.clone(); // Shallow copy
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
}
In Python:
import copy
class Prototype:
def clone(self):
return copy.copy(self) // Shallow copy
In Go:
type Cloner interface {
Clone() Cloner
}
type ConcretePrototype struct {
// ...
}
func (p *ConcretePrototype) Clone() Cloner {
out := *p // Shallow copy
return &out
}
And in Rust:
pub trait Clone {
fn clone_box(&self) -> Box<dyn Clone>;
}
#[derive(Clone)]
pub struct ConcretePrototype {
// ...
}
impl Clone for ConcretePrototype {
fn clone_box(&self) -> Box<dyn Clone> {
Box::new(self.clone()) // Shallow copy
}
}
This story expresses the main idea of the prototype design pattern: copying an existing object can be faster and more efficient than creating it from scratch. This is particularly useful when it’s necessary to create large and complex objects, or when an object needs to preserve a particular state. This pattern can make the code more readable and easier to maintain. When each object is copied, all properties and states are copied in the same way, which ensures consistency in the code.