Sobes.tech
Junior — Middle

Can you tell about a situation where you used the Prototype pattern in your projects?

sobes.tech AI

Answer from AI

The Prototype pattern is used when you need to create new objects by cloning existing ones, especially if creating an object from scratch is costly or complex.

In one project, I used the Prototype to create many similar object configurations with slight differences. Instead of manually filling all fields repeatedly, I implemented a clone() method that created a copy of the object, then only changed the necessary parameters.

Example in Java:

public class Config implements Cloneable {
    private String param1;
    private int param2;

    public Config(String p1, int p2) {
        this.param1 = p1;
        this.param2 = p2;
    }

    @Override
    protected Config clone() throws CloneNotSupportedException {
        return (Config) super.clone();
    }
}

// Usage:
Config original = new Config("default", 10);
Config copy = original.clone();
copy.param2 = 20; // only change what is needed

This sped up object creation and reduced code duplication.

Can you tell about a situation where you used the… - sobes.tech