Sample DAOFactory CFC
After my last post on Factory vs. Abstract Factory, I received an e-mail asking me how I'd implement a basic DAO factory. This is a basic template I use for most of my simple factories, customized to act as a DAO factory.
Its init() method takes a bean representing datasource information, and its create() method tries to create DAOs via a CFSwitch block.
The default action is to blindly create a DAO based on the name passed to create(), handing (a reference to) the datasource bean to the DAO's init() method. You'd probably want to try/catch this to get a meaningful error message when you're two or three API layers up an ask for a DAO you haven't yet created (I do this all the time!).
By adding a custom case to the switch, you can handle "special" creation cases. In this example, I've added a custom case to create a ContactDAO that's composed with an AddressDAO.
<cffunction name="init" access="public" returntype="DAOFactory">
<cfargument name="datasource" type="ModelGlue.Bean.CommonBeans.Datasource">
<cfset variables._datasource = arguments.datasource />
<cfreturn this />
</cffunction>
<cffunction name="getDatasource" access="private" returntype="ModelGlue.Bean.CommonBeans.Datasource">
<cfreturn variables._datasource />
</cffunction>
<cffunction name="create" access="public" returntype="any">
<cfargument name="name" type="string" required="true">
<cfset var result = "" />
<cfset var temp = structNew() />
<cfswitch expression="#arguments.name#">
<!--- Put "custom" DAOs in their own cases. --->
<cfcase value="contact">
<cfset temp.addressDAO = create("address") />
<cfset result = createObject("component", "ContactDAO").init(getDatasource(), temp.addressDAO) />
</cfcase>
<!--- By default, just try to create something by name --->
<cfdefaultcase>
<cfset result = createObject("component", arguments.name & "DAO").init(getDatasource()) />
</cfdefaultcase>
</cfswitch>
<cfreturn result />
</cffunction>
</cfcomponent>
5 comments - Posted by Joe Rinehart at 9:27 AM - Categories: ColdFusion MX