Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Design Patterns in ColdFusion: Singleton Pattern

Design Patterns in ColdFusion: Singleton Pattern

With the introduction of ColdFusion Components, or CFCs, in ColdFusion MX, we as ColdFusion developers have a way to leverage object-oriented programming, or OOP, within CFML.

Sometimes it is necessary in object-oriented programming to ensure that there is always one, but never more than one, of a certain object. There is also the need to access that single object from within any application. This idea of a single, globally accessible object has numerous programmatic advantages for us as developers.

It also makes the underlying J2EE memory management and garbage collection on which ColdFusion MX is built more efficient. And while CFCs are not the pure objects we may be familiar with in Java, they are an extremely useful object-like construct that we can utilize in several ways.

We can use CFCs as a static class library of related methods. We can use CFCs as a way to leverage Web services within ColdFusion, or we can even create a CFC object, or more precisely an "instance" in object-oriented terminology. We can then treat our CFC instance almost identically to an object in a language like Java. When working with CFCs we can create a single instance fairly easily. We can ensure that this one instance is accessible wherever necessary. In our example we will even make our CFC instance persist across multiple hits to the server. This is going to be fun!

Creational, Structural, and Behavioral
Last month we talked in some detail about the three types of design patterns: creational, structural, and behavioral. We also introduced our first structural pattern, the Composite pattern. The previous three articles in this series, Template Method, Iterator, and Strategy, were all behavioral patterns. The third type of patterns, creational patterns, deals with object creation.

Object-oriented programming concepts are relatively new to ColdFusion developers, so object creation as a concept, is totally foreign to us. To that end, this month we introduce our first creational pattern, the Singleton, with what is hopefully an example that will make sense of object creation as well as of the pattern itself.

There Can Be Only One
As with each previous article in this series I like to refer to the original "intent" of the pattern as laid out in the book Design Patterns: Elements of Reusable Object-Oriented Software. Clearly the preeminent work on the subject of design patterns, it is a must-read if you have an interest in mastering object-oriented programming. Its authors, the so-called "Gang of Four," established the general "intent" of the Singleton pattern to be the following:

"Ensure a class only has one instance, and provide a global point of access to it."

Well, that's actually pretty self-explanatory. We want one and only one instance of our CFC object and we want a way to access that CFC object from wherever we need to. In fact the Singleton pattern as a whole is at first glance somewhat easier to comprehend than many other design patterns. However, it is no less useful or powerful.

In a stateless Web environment, object creation is rarely an issue we need to deal with because every object that is "instantiated" is done behind the scenes and disappears again without us being any the wiser. We are not only going to create a Singleton CFC instance, we are also going to persist that instance across many pages and across many users.

Managing Applications in ColdFusion
ColdFusion developers have always controlled applications and application- specific data from within either a central Application.cfm file under the webroot (such as /inetpub/wwwroot/ on IIS) or within app-specific Application.cfm files within each application's directory. Inside these files we put everything from login and permission checks to setting application or request variables with static data that our application will need to run.

We also include a <CFAPPLICATION> tag, which allows us to define the scope of an application, allow session or client variables, and set application or session timeouts. We may go even further by having the app-specific Application.cfm files <CFINCLUDE> the webroot's Application.cfm file, which may set application or request variables for global data or data used by two or more applications. This is quite useful as it allows us to separate out common data, as opposed to duplicating the code, so we don't have a maintenance nightmare if any of that data happens to change. Another useful tool in working with application-specific data is XML configuration files.

XML Configuration Files
XML is everywhere these days and is being touted as a cure for all of your programmatic ills. Recently, as ColdFusion MX has taken hold with its new XML parsing capabilities, I have seen many discussions and recommendations with regard to using XML configuration files to store application-specific and/or global data. The XML file is read and parsed for every page request that is loaded on the server. In fact XML is becoming the standard repository for storing static attributes in Web development with both Java and .NET using XML configuration files extensively. I am not a proponent of using XML to store this kind of data, but it is an interesting idea that does seem to be gaining ground in the ColdFusion community.

The application management example we will be going over implements the Singleton pattern to ensure that there is one and only one CFC "object" in memory. It could use one or more XML configuration files to import static data into the CFC when it is instantiated. This data will need to be referenced in the application, but in our example we are hard coding the data as "properties" of the CFC.

Application Manager Base Class
The CFC that will make this all work for us is ApplicationMgr.cfc, shown in Listing 1. The CFC has two private structures, one called "App" and one called "My". The properties set into the App structure are the default settings for the <CFAPPLICATION> tag. These properties can be overridden in any application-specific CFC that extends ApplicationMgr.cfc. The execute() method outputs the <CFAPPLICATION> tag and any additional processing that you would normally include in Application.cfm. Alternatively, this additional processing, such as login or permission checks, should probably be placed in other functions within the CFC. This allows granular control over each method that can then be overridden in any future "derived" CFCs.

The properties set into the My scope effectively take the place of request or application scope variables. They are not put into the "this" scope so they are actually private variables that cannot be written over but can be accessed using the getValue() method passing in a single argument, which is the string name of the particular variable being accessed. An example is shown below:

<CFOUTPUT>#myApp.getValue("DSN")#</CFOUTPUT>

Last but not least we need the Singleton pattern to ensure that a maximum of one instance is created and that all calls to the ApplicationMgr.cfc return that same instance. To ensure you have the necessary control over the instantiation process it is normal to make the objects constructor private in Java or similar languages. Since CFCs do not have a classic constructor in the same way Java does we simply need to create an accessor method. An accessor method is a static method, in this case getInstance(), which will check to see if the global Singleton instance already exists and will instantiate it if it doesn't. Regardless, it then returns the reference to the CFC object to the calling page.

In this example we are storing our Singleton ApplicationMgr.cfc instance in the seldom-used Server scope, which allows the CFC instance to persist in memory on the server until ColdFusion Application Server is stopped or the actual server is rebooted. This allows us access to a persistent object from within our Web pages, which in and of itself is something of a rarity.

Now one thing to notice is that we first check to see if the server variable in which we are storing our Singleton object already exists and that it passes the IsStruct() test, which all CFC instances will. Then we put an exclusive lock on the variable using the <CFLOCK> tag. This ensures that once the first person instantiates the CFC, everyone else will get that same instance as well. We then check for existence again because someone may have been creating it as we were reading it initially.

Now that we have an exclusive lock we can know definitively whether or not it exists or whether it needs to be created. This type of locking is something common to multithreaded applications. In fact, the alternate name for multithreaded Singleton implementations is the Double Checked Locking Pattern.

Although the accessor method can create the Singleton, most of the time it will already exist in the Server scope when the accessor method is called. If some form of runtime information is needed, said processing is normally done inside the accessor method.

BillingAppMgr.cfc and QuoteAppMgr.cfc
As we examine the code for BillingAppMgr.cfc we notice that it doesn't actually do that much. We do override the applications name variable, which we store in the "App" scope. In addition we have added a DSN and ReportServer variable to the My scope so we can access them from within our application. Additionally BillingAppMgr.cfc overrides the getInstance() method because it needs to look for its application-specific server scope variable that will store its CFC instance. Code for BillingAppMgr.cfc is shown below and in Listing 2.

<cfcomponent extends="com.mycompany.ApplicationMgr"
displayname="BillingAppMgr">
<!--- App.* Stores Private Application Data
Accessible only within CFC --->
<cfparam name="App" type="struct" default="#structnew()#">
<cfset App.name = "Billing"><!--- "application_name" --->
<!--- My.* Stores Public Application Data
Accessible via GetValue("VarName") --->
<cfparam name="My" type="struct" default="#structnew()#">
<cfset My.DSN = "Billing"><!--- datasource name --->
<cfset My.ReportServer = "Crystal"><!--- Report Server --->
<cffunction name="getInstance" access="public"
returntype="struct" output="no">
<cfif NOT IsDefined("Server.ao__BillingAppMgr_AppObj") OR
NOT IsStruct(Server.ao__BillingAppMgr_AppObj)>
<cflock timeout="10" throwontimeout="No"
type="EXCLUSIVE" scope="SERVER">
<cfif NOT IsDefined("Server.ao__BillingAppMgr_AppObj") OR
NOT IsStruct(Server.ao__BillingAppMgr_AppObj)>
<cfset Server.ao__BillingAppMgr_AppObj = this>
</cfif>
</cflock>
</cfif>
<cfreturn Server.ao__BillingAppMgr_AppObj>
</cffunction>
</cfcomponent>

Now the Quote Application Manager works identically to the Billing Application Manager except with different App.Name, My.DSN, and My.ReportServer variables. Of course the InstanceID will also be different since they are different instances. The QuoteAppMgr.cfc is shown in Listing 3.

Application.cfm
Now with our application manager CFCs in hand what goes in Application.cfm? Well let's look at the billing system's Application.cfm because the billing system needs to access both billing and quote application-specific data. Application.cfm is shown below and in Listing 4:

<cfset Billing = CreateObject("component",
"com.mycompany.Billing.BillingAppMgr")>
<cfset Quote = CreateObject("component",
"com.mycompany.Quote.QuoteAppMgr")>
<cfset Billing = Billing.getInstance()>
<cfset Quote = Quote.getInstance()>
<cfset Billing.Execute()>

Well at five lines that's a pretty short Application.cfm. The first two lines create references to the BillingAppMgr and QuoteAppMgr CFC objects respectively. Lines 3 and 4 call the getInstance() methods for each of these returning the current Singleton objects regardless of whether they are newly created or have been sitting in server memory for weeks. The last line calls the execute method for Billing Application Manager because that's the actual application we are currently in.

The execute() method outputs the <CFAPPLICATION> tag, and any additional processing you may have normally added to Application.cfm. Now we can get application-specific data anywhere within our billing application, and even more exciting, to me at least, is the idea that we could add application-specific methods to our application manager CFCs. These methods need not be accessed only within Application.cfm; they can in fact be accessed anywhere within the application.

Testing the Singleton
The Singleton Application Manager example will output the InstanceID, DSN, and ReportSystem for each application. The code is shown below and in Listing 5:

<html>
<head>
<title>Singleton App Manager Example</title>
</head>
<body><br>Quote Application<br><br><br>
<cfoutput>DSN: #Quote.getValue("dsn")#</cfoutput>
<br><br><br><cfoutput>
InstanceID: #Quote.getValue("InstanceID")#</cfoutput>
<br><br><br><cfoutput>Report
System: #Quote.getValue("ReportSystem")#</cfoutput>
<br><br><br>Billing Application
<br><br><br><cfoutput>DSN: #Billing.getValue("dsn")#
</cfoutput>
<br><br><br>
<cfoutput>Instance ID: #Billing.getValue("InstanceID")#
</cfoutput>
<br><br><br>
<cfoutput>Report System: #Quote.getValue("ReportSystem")#
</cfoutput>
</body>
</html>

The InstanceID is useful for testing purposes to ensure that no matter how many page hits or sessions you open, you will always be looking at the same CFC instance. The InstanceID is simply a UUID created on instantiation. The output of the example is shown in Figure 1.

 

Runtime Information
If you need any runtime information, say the number of current users accessing the application, it can be stored as a variable and that variable can be accessed at any time or it can be determined programmatically on the fly when the getInstance() method is called.

A company I have consulted for uses a product called TeamStudio Screensurfer, which they use to access so-called "green screen" applications from their AS400 "mainframe." In May 2003, CFDJ ran a detailed review of the product ("Teamstudio Screensurfer: Bring screen-based applications to the browser in HTML format quickly and painlessly," Vol. 5, issue 5). This product can be used programmatically (explained in the review) or as a Web emulator.

When used as an emulator you need to maintain a constant connection from your client to the server. So if you have a five concurrent connection license it will only allow, you guessed it, five concurrent connections. You may want your application object to keep track of who has a session open and how long they have been working in it. For as long as our application object persists on the server, it can collect information, which is then accessible to us programmatically. We may want to give a "friendly" message to a prospective TeamStudio Screensurfer user saying that all five connections are being used and maybe list the current users and how long their current sessions have been active.

Conclusion
Whether you are maintaining a simple Web site or a complex n-tier application, you may come to the conclusion that a single "instance," no more and no less, of a certain CFC object is required. As the much-repeated quote from one of my favorite movies, the original "Highlander," (not those awful sequels mind you) puts so succinctly: "There can be only one." When dealing with the Singleton pattern there can be only one and that's exactly the way we want it.

More Stories By Brendan O'Hara

Brendan O'Hara is a software architect and CEO of Exos Technology LLC, a software consulting firm in the Philadelphia suburbs.
He co-authored the Advanced Macromedia ColdFusion MX Application Development, published by Macromedia Press, and was
technical reviewer for Programming ColdFusion MX by O'Reilly. Brendan is a Team Macromedia volunteer for
ColdFusion and chairman and founder of the Philadelphia Developers Network. [email protected]

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
SYS-CON Events announced today that Cedexis will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
SYS-CON Events announced today that Google Cloud has been named “Keynote Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
SYS-CON Events announced today that Opsani will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
SYS-CON Events announced today that Nirmata will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...