Sobes.tech
Junior — Middle

Can you give an example of a situation or task where the Prototype pattern is used for creating objects?

sobes.tech AI

Answer from AI

The Prototype pattern is used when creating a new object directly through the constructor is too costly or complex, and it is easier to clone an existing object.

Example situation:

In a game, there is a complex "monster" object with many settings and states. Instead of creating each monster from scratch, you can create one prototype monster and clone it, changing only the necessary parameters.

public class Monster implements Cloneable {
    private String type;
    private int health;

    public Monster(String type, int health) {
        this.type = type;
        this.health = health;
    }

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

    // getters and setters
}

// Usage:
Monster prototype = new Monster("Orc", 100);
Monster newMonster = prototype.clone();
newMonster.setHealth(80); // change only what is needed

This approach saves resources and time in creating objects with the same basic configuration.