[Forward]Selected Design Patterns - Singleton

From http://oreilly.com/flex/excerpts/enterprise-development-with-flex/selected-design-patterns.html

 

As the name singleton implies, only one instance of such a class can be instantiated, which makes such classes useful if you’d like to create some kinds of global repositories of the data so that various objects of your application can access them. In Chapter 1 , you saw examples of their use by various architectural Flex frameworks. For example, ModelLocator from Cairngorm provides a repository for the data that was retrieved by delegates so that the views can properly display it. But to get access to the data stored in this singleton, your application class has to first get a hold of this singleton:

var model: AppModelLocator = AppModelLocator.getInstance();

After this is done, you can access the data stored in various properties of the object to which the variable model refers.

If you need a Cairngorm singleton that can communicate with the server side, write the following code:

service = ServiceLocator.getInstance().getHTTPService( 'loadEmployeesService');

Pretty soon, your application code gets polluted with similar lines of code that try to get a reference to one of the singletons.

Here’s the idea. Why not just use a singleton that already exists in any Flex application instead of introducing new ones? This is a Flex Application object that’s always there for you because it is part of the Flex framework. Thus you can be fairly sure that there is only one instance of it.

The problem is that the Application class was not created as dynamic, and you need to either extend it to act as a singleton with specific properties, or make it dynamic to be able to add to the application singleton any properties dynamically. Example 2-1 ’s dynamic class DynamicApplication is a subclass of the Flex class Application. It implements a Dictionary that allows you to register your services with the application.

Example 2-1. DynamicApplication class

package com.farata.core{
	import flash.utils.Dictionary;
	import mx.core.Application;
	public dynamic class DynamicApplication extends Application implements
		IApplicationFacade{
			public function DynamicApplication(){
			super();
		}
		public static var services:Dictionary = new Dictionary();
	
	// Consider using getter and setter if you need to override behavior // but a workaround with "static" problem in Flex
		public function getService(name:String) : Object {  
			return services[name];
		}
		public function addService(name:String,value: Object): void {
			services[name] = value;
		}
		public function removeService(name:String) : void {
			delete services[name];
		}
		public function getServices() : Dictionary { 
			return services; 
		} 
	} 
}

This singleton class implements the IApplicationFacadeinterface (Example 2-2), which defines the methods to add, remove, and get a reference to the objects that are required by your application. The main reason to use the IApplicationFacade interface here is that when you typecast an Application with this interface in your code, you get Flash Builder’s “intellisense” support and compile-time error checking.

Example 2-2. IApplicationFacade interface

 


package com.farata.core {
    import flash.utils.Dictionary;
	public interface IApplicationFacade {
	function getService(name:String) : Object ;
	function addService(name:String,value:Object):void ;
	function removeService(name:String) : void ;
	function getServices() : Dictionary ;
    } 
} 

Note that the test program shown in Example 2-3 is no longer a regular <mx:Applica tion>, but rather an instance of the dynamic class shown in Example 2-1 and is located in thePatterns_lib project. Upon application startup, it calls the function addAllServices(), which dynamically adds myModel and myServices properties to the application object. Now any other object from the application can access this global repository just by accessing DynamicApplication.servicesfollowed by the property you are trying to reach. This is illustrated in the functions getData() and setData() used in Example 2-3 .

Example 2-3. The application Singleton.mxml


<?xml version="1.0" encoding="utf-8"?> 
<fx:DynamicApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" 
xmlns:fx="http://www.faratasystems.com/2009/components" 
creationComplete="addAllServices();"> 
<mx:Script>

<![CDATA[
import com.farata.core.DynamicApplication; 
import mx.core.Application; 
// Add required services to the Application object. // For illustration purposes, we'll add myModel and // myServices 
private function addAllServices() :void { 
// Add the model repository to the application object 
DynamicApplication.services["myModel"]= new Object(); 
// Add the services to the application object 
DynamicApplication.services["myServices"] = new Object(); 
} 
private function getData(serviceName:String, key:Object):Object{ 
return DynamicApplication.services[serviceName][key]; 
} 
private function setData(serviceName:String, key:Object, value:String):void{
DynamicApplication.services[serviceName][key]= new String(value); 
} 
]]> 
</mx:Script> 

<!--Adding values to myModel --> 
<mx:Button label="Add to myModel" x="193" y="59" 
click="setData('myModel',key.text, value.text)"/> 

<mx:Label x="14" y="42" text="Key" fontWeight="bold"/> 
<mx:Label x="14" y="14" fontWeight="bold" fontSize="14"> 
<mx:text> 
Add one or more key/value pairs to the object MyModel 
</mx:text> 
</mx:Label> 
<mx:Label x="91" y="42" text="Value" fontWeight="bold"/> 
<mx:TextInput x="8" y="59" id="key" width="75"/> 
<mx:TextInput x="89" y="59" id="value" width="96"/> 

<!--Retrieving the value from a Singleton. --> 
<mx:Button label="Show the value" x="8" y="122" click= 
"retrievedValue.text=getData('myModel', key.text) as String"/> 
<mx:Label x="135" y="121" width="95" id="retrievedValue" fontWeight="bold" 
fontSize="15"/> 
<mx:Label x="10" y="94" fontWeight="bold" fontSize="14"> 
<mx:text> 
Retrieve and display the value from MyModel bykey 
</mx:text> 
</mx:Label> 
</fx:DynamicApplication> 

As Figure 2-1 shows, this application displays a window in which a user can add any key/value pairs to the myModelobject located in the singleton DynamicApplication. Then you can access them by key by clicking on the button labeled “Show the value.”

The point of this exercise was to show how you can use a somewhat modified Flex Application object to create a global repository (a singleton) without the need to implement the singleton design pattern on your own.

 

你可能感兴趣的:(Flex,Flash,Access,Adobe,idea)