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
In his session at @ThingsExpo, Greg Gorman is the Director, IoT Developer Ecosystem, Watson IoT, will provide a short tutorial on Node-RED, a Node.js-based programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using a wide range of nodes in the palette that can be deployed to its runtime in a single-click. There is a large library of contributed nodes that help so...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
SYS-CON Events announced today that App2Cloud 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. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, will introduce two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a mu...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
Mobile device usage has increased exponentially during the past several years, as consumers rely on handhelds for everything from news and weather to banking and purchases. What can we expect in the next few years? The way in which we interact with our devices will fundamentally change, as businesses leverage Artificial Intelligence. We already see this taking shape as businesses leverage AI for cost savings and customer responsiveness. This trend will continue, as AI is used for more sophistica...
SYS-CON Events announced today that SourceForge has been named “Media 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. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
SYS-CON Events announced today that Massive Networks 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. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
SYS-CON Events announced today that DXWorldExpo has been named “Global 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. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that WineSOFT 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. Based in Seoul and Irvine, WineSOFT is an innovative software house focusing on internet infrastructure solutions. The venture started as a bootstrap start-up in 2010 by focusing on making the internet faster and more powerful. WineSOFT’s knowledge is based on the expertise of TCP/IP, VPN, SS...
SYS-CON Events announced today that Akvelon 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. Akvelon is a business and technology consulting firm that specializes in applying cutting-edge technology to problems in fields as diverse as mobile technology, sports technology, finance, and healthcare.
SYS-CON Events announced today that TechTarget has been named “Media 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. TechTarget storage websites are the best online information resource for news, tips and expert advice for the storage, backup and disaster recovery markets.
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...
SYS-CON Events announced today that Dasher Technologies 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. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we've...
DevOps at Cloud Expo – being held October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA – 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 r...
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, will present a step-by-step plan to develop your technology implementation strategy. He will discuss the evaluation of communication standards and IoT messaging protocols, dat...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" 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. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
Elon Musk is among the notable industry figures who worries about the power of AI to destroy rather than help society. Mark Zuckerberg, on the other hand, embraces all that is going on. AI is most powerful when deployed across the vast networks being built for Internets of Things in the manufacturing, transportation and logistics, retail, healthcare, government and other sectors. Is AI transforming IoT for the good or the bad? Do we need to worry about its potential destructive power? Or will we...
SYS-CON Events announced today that App2Cloud 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. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).