Created
June 15, 2012 14:34
-
-
Save steve-ross/2936770 to your computer and use it in GitHub Desktop.
Object Factory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<cfcomponent output="false" hint="Object Factory for Singleton instantiation"> | |
<!--- cleanup cache will only be called on every 500th call to the get function (will rehash the table) ---> | |
<cfset this.currentCacheInterval = 1 /> | |
<cfset this.cacheClearIntervalInMinutes = 180 /> | |
<cffunction name="init"> | |
<cfargument name="isDebug" type="boolean" required="false" hint="pass in true to reload every time" default="false" /> | |
<cfscript> | |
setCacheTime(); | |
// ObjectCache is a Java Hashtable: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html | |
Application.ObjectCache = CreateObject("java","java.util.Hashtable").Init(); | |
this.isDebug = arguments.isDebug; | |
return this; | |
</cfscript> | |
</cffunction> | |
<cffunction name="get" returnType="any" access="public" hint="gets an object singleton out of the hashtable cache"> | |
<cfargument name="object" type="string" required="true" hint="the object name"/> | |
<cfargument name="initArguments" type="struct" required="false" default="#StructNew()#" hint="the arguments to use to init the object"/> | |
<cfargument name="reload" type="boolean" required="false" default="false" hint="pass in true to reload the object in the cache"/> | |
<cfargument name="clear" type="boolean" required="false" hint="pass in true to clear the entire cache" default="false" /> | |
<cfscript> | |
var loc = arguments; | |
loc.key = loc.object; | |
loc.defined = Application.ObjectCache.Get(loc.key); | |
if(loc.clear){ | |
Application.ObjectCache.Clear(); | |
} | |
// ObjectCache is a Java Hashtable: see top | |
if (isDefined("loc.defined") && !loc.reload && !this.isDebug){ | |
return loc.defined; | |
}else{ | |
loc.obj = CreateObject("Component", "#loc.object#").init(argumentCollection=loc.initArguments); | |
Application.ObjectCache.Put(loc.key, loc.obj); | |
return loc.obj; | |
} | |
</cfscript> | |
</cffunction> | |
<cffunction name="setCacheTime" returnType="void" access="private" hint="resets the cache time"> | |
<cfset this.cacheTime = Now() /> | |
<cfset this.expireTime = DateAdd("n", this.cacheClearIntervalInMinutes, this.cacheTime)/> | |
</cffunction> | |
</cfcomponent> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment