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
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.