Java

Copying graphical shapes

Let’s take a look at how the Prototype can be implemented without the standard Cloneable interface.

shapes: Shape list

shapes/Shape.java: Common shape interface

package refactoring_guru.prototype.example.shapes;

import java.util.Objects;

public abstract class Shape {
    public int x;
    public int y;
    public String color;

    public Shape() {
    }

    public Shape(Shape target) {
        if (target != null) {
            this.x = target.x;
            this.y = target.y;
            this.color = target.color;
        }
    }

    public abstract Shape clone();

    @Override
    public boolean equals(Object object2) {
        if (!(object2 instanceof Shape)) return false;
        Shape shape2 = (Shape) object2;
        return shape2.x == x && shape2.y == y && Objects.equals(shape2.color, color);
    }
}

shapes/Circle.java: Simple shape

shapes/Rectangle.java: Another shape

Demo.java: Cloning example

OutputDemo.txt: Execution result

Prototype registry

You could implement a centralized prototype registry (or factory), which would contain a set of pre-defined prototype objects. This way you could retrieve new objects from the factory by passing its name or other parameters. The factory would search for an appropriate prototype, clone it and return you a copy.

cache

cache/BundledShapeCache.java: Prototype factory

Demo.java: Cloning example

OutputDemo.txt: Execution result

Last updated