If you don't clone in Java then what do you do

2019-04-20 02:14发布

Does anyone have any suggested or established best practices and naming conventions for copy constructors / factory methods etc in Java? In particular, say I have a class Thing and I want a method somewhere that returns a new Thing with the same value as a Thing passed in (or as the instance if it's an instance method). Would you have this as constructor or a static factory method or instance method? What would you call it?

As per the title, I want to avoid clone() and Cloneable.

标签: java oop
8条回答
三岁会撩人
2楼-- · 2019-04-20 03:00

I would call it a copy method or a copy constructor (as the case may be). If it was a static method, then I would call it a factory.

In terms of what to do, the most flexible and long living option is a copy constructor. This gives subclasses the ability to copy themselves just like the parent.

查看更多
走好不送
3楼-- · 2019-04-20 03:00

Another option is to implement the copying method in the source object, e.g.:

interface Has3DCoords {
    void setLocation(double x, double y, double z);

    void copyCoordsTo(Has3DCoords dest);
}

You would then implement copying with a piece of code like:

class Thing implements Has3DCoords {
    private Point3D loc;
    // ...

    void setLocation(double x, double y, double z) {
        loc.setLocation(x, y, z);
        // or: loc = new Point3D(x, y, z);
    }

    void copyCoordsTo(Has3DCoords dest) {
        loc.copyCoordsTo(dest);
        // or: dest.setLocation(loc.getX(), loc.getY(), loc.getZ());
    }

    OtherThing createOtherThing() {
        OtherThing result = new OtherThing();
        this.copyCoordsTo(result);
        return result;
    }
}

This can be useful if:

  • It does not make sense to clone the whole object
  • There is a group of related properties that are often copied as one unit
  • You do not want to expose loc as a property of Thing
  • The number of properties is large (or there are many such groups) so a constructor that required all of them as parameters would be unwieldy.
查看更多
登录 后发表回答