CSE Roadmap

Common tier · about 2 hours · 6 parts

Part 4 of 6 · 3 min read

Copy constructors

A safer way than Cloneable.

Java has a built-in route to copying: the Cloneable interface and the clone() method. EJ advises caution. The interface has no clone method of its own, and Object.clone is protected, so implementing the interface does not let anyone call it. It changes the behaviour of a method on a superclass, which EJ calls a highly unusual use of an interface. EJ describes the mechanism as fragile, dangerous and outside the normal rules of the language, since it creates objects without calling a constructor. It also needs unenforced rules to be followed by the class and every superclass above it.

EJ's recommendation is a copy constructor, a constructor that takes one argument of its own class, or a copy factory, its static factory twin. The MeetingTemplate(MeetingTemplate o) constructor above is one. EJ lists the advantages: no dependence on risky object creation, no unenforceable rules, no conflict with final fields, no unnecessary checked exceptions and no casts. A copy constructor can also take an interface type. For example, new TreeSet<>(s) copies any set into a sorted set, and clone cannot offer that. EJ's one exception is arrays, which are best copied with clone.

Now the pattern itself. A registry stores prototypes by key and hands out copies.

interface Prototype<T> { T copy(); }

class Registry {
    private final Map<String, MeetingTemplate> protos = new HashMap<>();

    void register(String key, MeetingTemplate t) { protos.put(key, t); }
    MeetingTemplate create(String key) { return protos.get(key).copy(); }
}

With MeetingTemplate implementing Prototype<MeetingTemplate> by returning new MeetingTemplate(this), a call to create("standup") returns a fresh object. Setting its title to "Standup (Friday)" leaves the stored prototype titled "Standup". GoF notes two benefits here. Products can be added and removed at run time by registering a sample. And new kinds of objects can be defined by varying values and not by writing new classes, which reduces the number of classes.

Compared with factories: Factory Method needs a creator class for each kind of product, while a prototype only needs a sample and a way to copy it. Compared with a builder: a builder constructs from settings, while a prototype starts from a finished object and edits it.

Common mistake

Copying only the top-level object and sharing the lists inside it. Test every copy by changing a nested value and checking that the original is untouched.

Interview angle

Answer in your head first, then open it.

What is the Prototype pattern?

New objects are made by copying a sample object, so the client does not need to know the class.

Shallow versus deep copy?

A shallow copy shares inner objects. A deep copy duplicates the mutable ones too.

Would you use clone?

Rarely. A copy constructor or copy factory is safer, as EJ advises.

Check yourself: 1. What does the registry's create("standup") return? 2. What is EJ's one exception for clone? 3. Name two advantages of a copy constructor.