PDA

View Full Version : Class problem


Dart
04-16-2008, 02:33 PM
Hi there,:D

I just wonder, how can i create class that will have only one instance and in this class there will be possible to be subcribed in it by another class. Is it possible ? If is, than how :] ? thyank you very much for helping.

wvxvw
04-16-2008, 03:32 PM
Create static private property in the class of boolean type, once the first instance was created - set it to true, and when you attempt to create another instances - check it. If check fails - make constructor thow an error.

dimpiax
04-16-2008, 04:06 PM
wvxvw
Demonstrate an example it's hard for u?

Dart
Look, this pattern of designing called Singelton
Here's example of Yarovoy (http://yarovoy.com/2007/10/24/singleton_in_actionscript_3/)


package
{
/**
* Example of realization of pattern Singleton on ActionScript 3.0
* with creation instance at initialization stage of class.
*
* @author Yuri "Barmaley" Yarovoy
* @version 1.0
*/
public class Singleton
{

// Link at single instance of class
private static var __instance:Singleton = new Singleton();

/**
* Return link at single instance of class
*/
public static function get instance():Singleton
{
return __instance;
}

/**
* Constructor.
*/
public function Singleton()
{
if(__instance)throw new Error("You cannot create more than one instance of this class. For access use: Singleton.instance.");
}
}
}

Translation by Dmytro Pilipenko :rolleyes:

jaga
04-16-2008, 04:58 PM
look into singletons. wvxvw's method works, but won't throw a compile-time error, so isn't as elegant as some other singleton workarounds

Edit: better like this:


package
{
public class MyClass
{
private var _classInstance:MyClass

public function MyClass(initator:SingletonLock):void
{

}
public function getInstance():MyClass {
if (!_classInstance) {
_classInstance = new MyClass(new SingletonLock());
}
return _classInstance;
}
}
}

class SingletonLock {
}


so essentially, you now have a private constructor, since any public access will throw a compile-time error

dimpiax
04-16-2008, 05:06 PM
jaga
Man u funny.. a go under table.

wvxvw
04-16-2008, 05:46 PM
jaga:
public function getInstance()
this function has to be either static, or you'll never be able to call it %)
or remove strict type declaration here... public function MyClass(initator:*)