Published by Niels on 16 Mar 2006 at 08:21 pm
A storage pattern
Every time I build software that makes use of a Model-View-Controller pattern I always have the feeling that the wheel is being re-invented with regards to the View part (and to a lesser extent the Model part as well). This is caused by the fact that, to me, the most obvious solution for a view is a tree-structure of elements that share a single interface so that a simple draw() on the top-most interface is sufficient enough to get the whole tree drawn (to screen, file, paper, etc. but that will be for a later story).
The pattern below is what I always use to implement this:
This makes it very easy to create objects that either store a single element that is drawn, or multiple elements that are drawn. You have to choose if the concrete element is either a SingleElement storing ‘content’ or a ContainerElement that can store other elements. This way it is very easy to build a tree of similar objects that have a shared interface. This pattern is more commonly known as the Composite Pattern.
The diagram is drawn using Dia. The original diagram source can be found here.