There are two ways to implement this.
The first is by passing an argument to the accessor method that specifies which instance is desired. That structure looks like this:
The second approach is to use a separate accessor methods for each separate instance. That structure looks like this:
The first approach is preferred when there are many (though finite) instances or when the instances easily map onto a particular argument type (for example, one instance for positive values of the argument and one for negative values). The second approach is preferred when there are relatively few instances and the instances do not closely map onto an obvious argument type. The ultimate decision depends on how you are using this pattern.
A Dual class implemented in Java that uses the first approach
public class Dual1 {
static Dual1 instance1 = new Dual1();
static Dual1 instance2 = new Dual1();
protected Dual1() { }
public static Dual1 getInstance(int which) {
if(which != 1 && which != 2) {
throw new IllegalArgumentException(which +
" is not a valid instance. Only 1 and 2 are valid");
}
if(which == 1)
return instance1;
else
return instance2;
}
}
A Dual Class implemented in Java that uses the Second Approach
public class Dual2 {
static Dual2 instanceA = new Dual2();
static Dual2 instanceB = new Dual2();
protected Dual2() {
}
public static Dual2 getInstanceA() {
return instanceA;
}
public static Dual2 getInstanceB() {
return instanceB;
}
}
A Dual class implemented in C++ that uses the first approach