The Singleton Pattern
SIngletons are nearly universal amongst object oriented programming languages, but for each language someone had to work out how to write it. So that's what I've done — the first ever Singleton implementation in Kite.
class Singleton [ property stored_instance, construct () [ exp = make System.exceptions.AccessDenied( "Cannot directly instanciate a Singleton." ); exp|throw(); ], construct (create) [], method get_instance () [ decide [ (this.stored_instance is System.null) [ this.stored_instance = make this(true); ]]; this.stored_instance; ] ]; class Test from Singleton []; test = Test|get_instance(); test|print;
Points of interest:
- To prevent the Singleton from being instantiated by accident we throw an exception in the default constructor.
- We also need a constructor that doesn't throw an expection, or we'd never be able to instantiate the class.
Written by Rowan Lewis on Thursday 5th of February, 2009