How to extend a Singleton

The answer is easier than you think. If you stop and ponder how extending a class works, it makes sense that when the subclass calls super() that it works since it’s just a plain old constructor, except that it’s private, but that doesn’t have any effect in this situation. Basically you side-step the static getInst() call. Here’s an example:
class MySingleton {
 private static var inst:MySingleton=null;
 private fucntion MySingleton() {}
 public static function getInst():MySingleton {
  return MySingleton(inst?inst:inst=new MySingleton());
 }
}
Now let’s extend that:
import MySingleton;
class MyExtendedClass extends MySingleton {
 public function MyExtendedClass() {
  super();
 }
}
That’s it, it’s really that easy. Stay tuned for how to kill a Singleton.

Comments are closed.