Polymorphism
Polymorphism simply means that you can substitute objects which have a common super class and the code will still work.
<cfcomponent output="false" hint="I represent a Shopping Basket"> <!--- constructor ---> <cffunction name="init" access="public" returntype="Product" output="false" hint="I am the constructor"> <cfset variables.instance = StructNew() /> <cfset create() /> <cfreturn this /> </cffunction> <!--- public methods ---> <cffunction name="addProduct" access="public" returntype="void" output="false" hint="I override the getSku() method of the superclass"> <cfargument name="Product" required="true" hint="I accept a Product object or sub-class of Product" type="Product" /> <cfset ArrayAppend( variables.instance.items, arguments.Product ) /> </cffunction> <cffunction name="getItems" access="public" returntype="array" output="false" hint="I return an array of Products in the basket"> <cfreturn variables.instance.items /> </cffunction> <!--- private methods ---> <cffunction name="create" access="private" returntype="void" hint="I create an empty array" output="false"> <cfset variables.instance.items = ArrayNew( 1 ) /> </cffunction> </cfcomponent>
<!--- create a DVD ---> <cfset properties = StructNew() /> <cfset properties.sku = 12345 /> <cfset properties.price = 9.99 /> <cfset properties.title = "The Shawshank Redemption" /> <cfset properties.description = "Andy finds that survival comes down to a simple choice: get busy living or get busy dying." /> <cfset properties.region = 2 /> <cfset properties.duration = 2.16 /> <cfset DVD = CreateObject( "component", "DVDProduct" ).init( properties ) /> <!--- create a Book ---> <cfset properties = StructNew() /> <cfset properties.sku = 67890 /> <cfset properties.price = 30.99 /> <cfset properties.title = "ColdFusion 8 Developer Tutorial" /> <cfset properties.description = "This book is the most intense guide to creating professional ColdFusion applications available." /> <cfset properties.isbn = "978-1847194121" /> <cfset properties.pages = 400 /> <cfset Book = CreateObject( "component", "BookProduct" ).init( properties ) /> <!--- Although Book & DVD are different Objects we can still pass them to Basket ---> <cfset Basket = CreateObject( "component", "Basket" ).init() /> <cfset Basket.addProduct( Book ) /> <cfset Basket.addProduct( DVD ) /> <!--- get items in the basket ---> <cfset items = Basket.getItems() /> <cfoutput> <h2>Your Basket</h2> <cfloop from="1" to="#ArrayLen( items )#" index="index"> <cfset Product = items[ index ] /> #Product.getTitle()# (#Product.getSku()#)<br /> £#NumberFormat( Product.getPrice(), "9.99" )# <hr /> </cfloop> </cfoutput>