Example: I have several types, e.g. Wheel, Brake, Engine, Clutch, AutoBox, ManualBox, ElectricWindow, RearParkingSensor, HeatedSeats. These will all inherit a ICarPart marker interface (could be an attribute (java annotation), but doesn’t matter at this stage).
I then write my Car class that can represent all car types, e.g.
class Car { string Name; DateTime creationDate; string ID; IList<ICarPart> parts; }
I then write a factory to create cars. The factory could refer to some XML which is an ingredients list for different car types. E.g. (and please ignore format, this is just for illustration):
<ExpensiveCar> <Name>Expensive Car</Name> <Parts> <HeatedSeats/> <Wheel count=4/> <RearParkingSensor/> <ElectricWindow type=FrontAndBack/> </Parts> </ExpensiveCar>
The factory would parse this ingredients list and create the car object. New car types would be available to the system providing the parts had been coded and the ingredient list XML written.
Questions:
- What is this pattern called? Or is it just multiple patterns combined?
- Is any of this an antipattern?
- How do I represent this in a UML? I could do a class diagram for the parts and for the base car class. How would I show the instances of that class that are currently supported and the parts they have?
Thanks in advance. If any of this is unclear please comment and I’ll amend/udpate/provide more details.
The pattern described is the Builder Pattern. The builder pattern builds complex objects from a set of simpler parts. Sometimes the objects built by the builder pattern are Composite Objects (though not neccessarily in the question’s case).
The builder pattern is often demonstrated using hard coded ingredients lists, though there is nothing in the pattern that requires this, nor does there seem to be a specific pattern documented describing the ‘ingredients list’ approach.
No
Probably by:
Note that because this is an instance the text ‘ExpensiveCar : Car’ should be underlined but SO doesn’t allow me to do this.
The notation I’ve used here to initialise an array with parts isn’t great and might not be the best approach. Perhaps an alternative would be to add a UML note containing the actual XML. The important thing is that a client can see what makes an expensive car and so can a programmer.