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
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Conference Guru has been named “Media Sponsor” of the 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to gre...
The Internet of Things will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, demonstrated how to move beyond today's coding paradigm and shared the must-have mindsets for removing complexity from the develop...
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...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
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 ...
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...