Relating
objects with composition
Inheritance (also called a "specialization relationship")
is very powerful, yet the "is a" relationship
is only one way that objects can relate to each other. Usually,
one object has another object for one of its properties.
In this relationship, the operative phrase is "has
a," as in a Person
has an Address.
Such relationships between objects are called composition.
In the case of the Person
object, without using composition, you might model it as
follows:
<cfcomponent hint="I am a Person">
<cfset this.firstName = "">
<cfset this.lastName= "">
<cfset this.address1 = "">
<cfset this.address2 = "">
<cfset this.city = "">
<cfset this.province = "">
<cfset this.postalCode = "">
</cfcomponent>
Of course, you have to write methods for retrieving and
setting individual variables—getters and
setters, as they're called. This is not difficult,
however.
Below is a sample getter and setter for a single property,
address1:
<cffunction name="getAddress1" returntype="string">
<cfreturn this.address1>
</cffunction>
<cffunction name="setAddress1">
<cfargument name="address" required="yes" type="string">
<cfset this.address1 = arguments.address>
</cffunction>
<!--- more getters and setters below --->
Create getters and setters for all the properties of Person.
Note that you now have another CFC called Venue:
<cfcomponent hint="I am a
Venue">
<cfset this.venueName = "">
<cfset this.costPerDay= 0>
<cfset this.address1 = "">
<cfset this.address2 = "">
<cfset this.city = "">
<cfset this.province = "">
<cfset this.postalCode = "">
</cfcomponent>
Hmmm…Venue, too,
needs address information. This means that you'll end up
writing identical getter and setter code that uses the addresses
properties in both Venue
and Person. A better
method would be to create a separate CFC called Address
and relate that to Person
by means of composition. The following UML class diagram
shows the relationship: |