Featured Post

Flex 3 Certification Mock tests

if you haven’t already heard of  it, PXL designs has released Attest 1.5 which is a tool built in adobe AIR that provides mock tests for Flex 3. Unlike Attest 1.0 which was not free, this is a free version which provides 3 full length tests of 50 questions each and 5 mini tests of 25 questions...

Read More

AS3 Singleton class with parameterised constructor

Posted by ravi | Posted in Customization, flex | Posted on 23-02-2010

Tags: ,

0

As many of you already know, in AS3 there is no direct way to create singleton class i.e there is no keyword Singleton or any other equivalent keyword using which this can be accomplished. But there is a simple work around to create singleton class. The code below shows this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Services extends EventDispatcher
{
public static function getInstance(url:String) : Services
{
if ( servicesLocator == null )
{
servicesLocator = new Services(url);
}

return servicesLocator;
}

public function Services(url:String)
{

if ( servicesLocator != null )
{
throw new Error( "Only one Services instance should be instantiated" );
}
ENDPOINT_URL=url
gateway=new HTTPService();
gateway.resultFormat="e4x";
gateway.url = ENDPOINT_URL;
gateway.method = "POST";
gateway.useProxy = false;
gateway.addEventListener(ResultEvent.RESULT, resultHandler);
gateway.addEventListener(FaultEvent.FAULT, faultHandler);
}
}

the way to create object now is like this:

1
public var servicesInstance:Services =Services.getInstance("serviceURL.php");

we’re defining here a static function called getInstance which calls the constructor only if servicesLocator object is null or not initialized already. A sinlgeton class is particularly of high use for HTTPService object as it allows single point of handling all the requests in this way.