Prototype Pattern
The prototype pattern is a creational pattern that allows cloning of objects, even complex ones, without coupling to their specific classes. This pattern is particularly useful when the cost of creating a new instance of a class is expensive or complicated.
We can implement the pattern using the Clone trait.
#[derive(Clone)] struct Prototype { field1: String, field2: i32, } impl Prototype { fn new(field1: String, field2: i32) -> Self { Prototype { field1, field2 } } fn clone_prototype(&self) -> Self { self.clone() } } fn main() { let original = Prototype::new(String::from("Prototype"), 42); let cloned = original.clone_prototype(); println!("Original: {} - {}", original.field1, original.field2); println!("Cloned: {} - {}", cloned.field1, cloned.field2); }
- We define a
Prototypestruct with two fields. - We derive the
Clonetrait for thePrototypestruct, which provides theclonemethod. - We implement a
clone_prototypemethod that clones the current instance. - In the
mainfunction, we create an instance ofPrototypeand then clone it using theclone_prototypemethod.