Are there any alternatives to implementing Clone in Java?

前端 未结 5 1165
醉酒成梦
醉酒成梦 2021-01-12 15:10

In my Java project, I have a vector of various types of Traders. These different types of traders are subclasses of the Trader class. Right now, I have a method that takes a

5条回答
  •  生来不讨喜
    2021-01-12 15:48

    One way is to make it a final class like Java's own String, which will make any change to an object of class Trader to create a new copy in memory, but it will make it impossible to subclass it.

    Another (better) way is to use a factory method to create and copy Trader objexts, which implies that you must not allow for the default constructor to be used i.e. make it a private. This way you can control the number of instances the class has. See http://en.wikipedia.org/wiki/Factory_method

    public class Trader {
    
        /* prevent constructor so new cant be used outside the factory method */
        private Trader() {
        }
    
        /* the factory method */
        public static Trader createTrader(int whatKindOfTrader) {
    
            switch (whatKindOfTrader) {
            case 0:
                return new Trader1(); // extends Trader
            case 1:
            default:
                return new Trader2(); // extends Trader
            }
            return new Trader3(); // or throw exception
        }
    }
    

    You might even specify another overloaded method, or a second argument that takes one Trader and copies it into a new one, thus replacing clone. Btw, you might want to override the clone() method and throw CloneNotSupportedException, to prevent default Object cloning.

提交回复
热议问题