Composite vs Decorator Patterns

In Java world (yes, I know, there is such world ostensibly …), there’s a templating framework called Tiles. It’s basically an open source framework to help developers build View part of the MV* (* = whatever).

Tiles uses Composite pattern, much like what you see in ASP.NET MVC.

The other side of the coin is Decorator pattern. SiteMesh is an example of Decorator pattern, it is also a Java open source template framework to build View. In .Net world, SiteMesh is equivalent to classic ASP’s master page concept.

Composite vs Decorator

Both Composite and Decorator break layout to smaller components (or sections), such as Header, Menu, Content and Footer. Each of these components is built on separate page (.jsp file in the case of Java).

When the page is requested, it will take all needed components and put them together as a page. The difference between Composite and Decorator is on the way the page is constructed.

Composite allows the children components to define what’s needed. For example, when you load a Contact page, you tell the framework that the main component to load is Contact. The framework knows Contact component needs Header, Content and Footer components. It will then load all the dependencies components, stick them into Contact component. The page is complete and returned to user.

Decorator, on the other hand, relies on the parent (or master page) to define what’s needed for a page. Taken from Contact page example above, Decorator will first see which parent component the Contact is using, then call the parent component. From there, it knows the parent’s dependencies, construct the parent component along with its dependencies, then stick the Contact component into parent component where it belongs. In this case, the parent component also define where the main component should be placed.

More differences from Tiles project site.

Aspect Composite View Decorator
Reusability The different parts of the page (template and pieces) can be reused across the whole application. Each decorator can be reused, but the decoration itself can be applied to one page at a time.
Ease of configuration Each page must be defined explicitly. The decorator can be applied even to the entire application.
Runtime configuration The pages can be configured and organized at runtime Since one page is decorated at a time, this feature is not present.
Performances Low overhead for composition. The page to be decorated has to be parsed.

Decorator Problem

One problem I had before was trying to build a reusable web component, think about Calendar widget. I would be fine if I build my widget with pure HTML and JavaScript, but if there is a special case where I need to use View framework to load up my widget, then Decorator wouldn’t be much useful because I can’t have children component to use my widget without repeating code.

That’s not to say Composite doesn’t have any problem, I just haven’t come across one.