All pastes #178593 Raw Edit

Anonymous

public text v1 · immutable
#178593 ·published 2006-09-21 12:11 UTC
rendered paste body
/**------------------------------------------------------------------------------------------------
	
	@modifies	Obj
	@brief		Creates a singleton out of any class.
	
-------------------------------------------------------------------------------------------------*/
	
	uses "reflection", "array";
	
/*------------------------------------------------------------------------------------------------*/
	
	class ErrorSingleton extends Error {}
	
	class modifies Obj {
		directive Singleton() {
			.Singleton("instance");
		}
		
		directive Singleton(string setup) {
			eval("
			class modifies ${Class.name(self)} {
				static private object singletonInstance;
				static private boolean singletonCreating;
				
				constructor() {
					// Are we creating an instance:
					if (!.getClass().singletonCreating) {
						raise new ErrorSingleton('You cannot create new instances of Singleton classes directly.', 1);
					}
					
					// Use the pseudo constructor:
					.$setup();
				}
				
				static function getInstance() {
					void singletonClass = self;
					
					// Allow instance creation:
					.singletonCreating = true;
					
					// Create the instance:
					.singletonInstance = new singletonClass();
					
					// Disable instance creation:
					.singletonCreating = false;
					
					return .singletonInstance;
				}
			}");
		}
	}
	
/*------------------------------------------------------------------------------------------------*/
	
	class Test {
		[Singleton];
		
		function instance() {
			object request = new Request();
			
			request.print("instance()");
		}
		
		function test() {
			object request = new Request();
			
			request.print("test()");
		}
	}
	
/*------------------------------------------------------------------------------------------------*/
	
	//object test = new Test();
	object test = Test.getInstance();
	test.test();
	
/*------------------------------------------------------------------------------------------------*/