It’s sorta, kinda, like…
I’ve always been vaguely aware of the factory design pattern, but I’ve actually only started using it in earnest in the last few months. The factory design pattern is used whenever you need to create an instance of a class, but the specific class you require an instance of is not known until runtime. But what exactly does that mean? I’m a great believer in learning by example, so I took the opportunity to write this blog in an attempt to demystify what I’ve found to be a really useful way of compartmentalising my code.
At the heart of the factory model is an abstract class. This is a template class from which a number of variants are derived (it’s the job of the factory to provide the correct variant at runtime, but more on that in a bit). Let’s assume we are designing a system for an insurance company. They may have use of an abstract class such as the one below:
That is, an insurance policy has an ID, an insured party, start and end date and a property indicating the total value of goods insured by the policy. Now let’s assume that our insurance company offer both motor and property insurance. Consequently, they may have classes that look like those below:
These classes are variants on the Policy class, each with properties relevant to the variant:
- the motor policy maintains a list of insured vehicles, and defines our TotalInsuredValue property as the sum of the value of all insured vehicles
- the property policy maintains a list of insured properties, and defined our TotalInsuredValue property as the sum of the value of all insured properties, including contents value if the property has contents insured also.
Imagine the first screen of our application – what type of policy do you require? Our factory comes into play whenever we need to provide the correct variant thus:
With common fields gathered, the user is then redirected the the appropriate area of the application – that is, the user will be redirected to an area where they can enter the details of the vehicles or properties to be insured, dependent upon the policy type.
Listing Customer Policies
And now the beauty of the abstract class approach – we can write code such as the following:
Note that each Policy will call the appropriate method to get the value of TotalInsuredValue dependent on the specific Policy class. In this way, we can extend the system and offer new policy types without interfering with existing types – let’s say we now offer insurance for mobile phones:
The above model allows new products to be added into the system in isolation. This is especially useful when you have multiple development teams, each working on a different product to be released in the same development cycle, not to mention production support catering for existing products that require bug fixes after go-live.
Of course, this is not the only applicable design pattern for such a system, but I hope I’ve made this one clearer.