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.


IoT & Smart Cities Stories
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...