DEV Community

AK
AK

Posted on

Prototype (Clone)

What is Prototype design pattern?

Prototype is a creational design pattern that lets you copy existing objects without making your code dependent on their classes.
The existing object acts as a prototype and contains the state of the object. The newly copied object may change same properties only if required.
This approach saves costly resources and time, especially when object creation is a heavy process.

clone


Prototype Design Participants

  1. Prototype
    This is the prototype of an actual object

  2. Prototype registry
    This is used as a registry service to have all prototypes accessible using simple string parameters

  3. Client
    Client will be responsible for using registry service to access prototype instances

clone


When to use the Prototype Design Pattern

  1. Your code shouldn't depend on the concrete classes of objects that you need to copy

  2. You want to reduce the number of subclasses that only differ in the way they initialize their respective objects

  • When a system should be independent of how its products are created, composed, and represented
  • When the classes to instantiate are specified at run-time. For example,
    1. By dynamic loading or To avoid building a class hierarchy of factories that parallels the class hierarchy of products or
    2. When instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.

Code Examples

main.rs

// use clone to use clone method
#[derive(Clone)]
struct Circle {
    pub x: u32,
    pub y: u32,
    pub radius: u32,
}

fn main() {
    let circle1 = Circle {
        x: 10,
        y: 15,
        radius: 10,
    };

    // Prototype in action.
    let mut circle2 = circle1.clone();
    circle2.radius = 77;

    println!("Circle 1: {}, {}, {}", 
               circle1.x, 
               circle1.y, 
               circle1.radius
    );
    println!("Circle 2: {}, {}, {}", 
               circle2.x, 
               circle2.y, 
               circle2.radius
    );
}
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)