Skip to Navigation Skip to Content

In my previous post I explained the use of remote proxies to access Singletons in Application scope. I thought that I would elaborate what a Singleton is for those who might be late to the design pattern party (better late than never!). A Singleton is a design pattern where an object is instantiated … wait for it … a single time. That’s right the object is created only once and is stored in a scope where it can be globally accessed.

A Singleton can reside in any persistent scope that can store complex data types. In ColdFusion these include the Application, Session and Server scopes.  It is important to note that a Singleton’s state should not change after instantiation to avoid race conditions.

A good candidate for using the Singleton pattern includes objects that coordinate actions within the application -- objects such as Services. The following is an example where we instantiate a ProductService object as a Singleton on application start up and then store it in the Application scope.

Application.cfc

<cfcomponent output="false">
 
    <cfscript>
        this.name = "SingletonExample";
        this.applicationTimeout = CreateTimeSpan(2,0,0,0);
    </cfscript>
 
    <cffunction name="onApplicationStart" output="false" returntype="void">
        <cfscript>
            var productGateway = CreateObject( "component", "com.ProductGateway" ).init( "Demo" );
            APPLICATION.productService = CreateObject( "component", "com.ProductService" ).init( productGateway );
        </cfscript>    
    </cffunction>
    
</cfcomponent>

The reason we are creating the Singleton in the onApplicationStart() method is to ensure that there is exactly one instance of the component for the lifetime of the Application. In order to ensure it remains a Singleton there should be no other place in our application that we create another instance of the ProductService object.

Once our ProductService Singleton is created we would then be able to access it anywhere within the application by accessing the object from in the Application scope.   

<cfset APPLICATION.productService.getProducts() />

As you can see it’s very simple to implement the Singleton pattern into your Applications. The complexity increases when managing the dependencies between objects and instantiating the objects only when needed. In a future post I will go over using ColdSpring to manage the dependencies between your Singletons and the use of lazy-loading to defer instantiation of objects until it is needed.

Posted under: ColdFusion , Design Patterns

0 responses to “The Singleton Pattern and ColdFusion”

Leave a comment