Friday, August 31, 2012

Failed Singleton Base Class

Failed Singleton base class:
package com.JM.baseClasses.designPatterns.singleton_baseClass{
 
 //A singleton pattern baseclass.
 //for any object that should never have
 //more than one instance.
 
 public class Singleton_BaseClass {
  
  private static var oneInstanceExists:Boolean = false;

  public function Singleton_BaseClass() 
  {
   if(oneInstanceExists){
    throw new Error("classes that derive from singleton can only be instantiated ONCE.");
   }else{
    oneInstanceExists = true;
   }//[x]
   
  }

 }//class
}//package
The idea was to make multiple singleton classes that could extend from this base class. And make it so you could only have ONE instance of each unique singleton class. This base class did not work, because all classes that extend from "Singleton_BaseClass" share the same static variables. I was hoping each class that extended from the "Singleton_BaseClass" would get a UNIQUE copy of the static variable "oneInstanceExists". This has not been the case. Idea to make this work: Make "oneInstanceExists" a dictionary instead of a boolean. Make classes derived from "Singleton_BaseClass" self-identify their type and load that type into the dictionary. The base-class constructor will check to make sure the type does not already exist in the dictionary. If it does, we throw an error.

1 comment:

  1. Hmm... Might be best to do it component based.
    Have a class called "singleton_master"
    that has a static dictionary and a static
    function that is called in the constructors
    of any class that is supposed to be a singleton.

    ReplyDelete