Singleton Pattern   «Prev  Next»

Dual Pattern - Exercise Result

You entered:
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:
Dual Pattern consisting of first instance and second instance
Dual Pattern consisting of first instance and second instance
The second approach is to use a separate accessor methods for each separate instance. That structure looks like this:

Dual class consisting of instance A and instance B
Dual class consisting of instance A and instance B

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.
Java
C++

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


class Dual1 {
  protected:
  Dual1(){};
   static Dual1* instance1;
   static Dual1* instance2;
 
  public:
   static Dual1* getInstance(int which);
};
Dual1* Dual1::instance1 = 0;
Dual1* Dual1::instance2 = 0;
Dual1* Dual1::getInstance(int which) { 
 if(0 ==instance1) {
   instance1 = new Dual1();
 }
 if(0 == instance2) {
   instance2 = new Dual1();
 }
 if(1 == which) return instance1;
   else return instance2;
}

Since exceptions are somewhat more complicated in C++ than Java, I have simply made instance2 the default.

A Dual Class implemented in C++ that uses the Second Approach


class Dual2 {
 protected:
  Dual2(){};
  static Dual2* instance1;
  static Dual2* instance2;
  public:
   static Dual2* getInstance1();
   static Dual2* getInstance2();
};
Dual2* Dual2::instance1 = 0;
Dual2* Dual2::instance2 = 0;
 
Dual2* Dual2::getInstance1() {
 if(0 == instance1) {
  instance1 = new Dual2;
 }
 return instance1;
}