What is the difference between a mixin and the decorator pattern?

A mixin is apt when you’re adding some behavior to your class. e.g. the ability to enumerate in case of a collection type. You can mixin as many sets of behavior into your class as you want. Its a nice way to reuse common code ; you basically get a bunch of methods for free.

A decorator on the other hand is more of a sneaky interceptor. It exposes the same public interface as the target object, contains a target object to which it delegates all client calls ; however it decorates the call with some pre and/or post processing. e.g. if I’m writing code against a MyCollection and I want all calls to this type to be logged. I could derive a new decorator MyCollectionWithTimeStampedLogging both deriving from an ICollection base so that they look identical to the client. The decorator would take an instance of ICollection as a ctor param and delegate calls to it. e.g. Add would look like this

public void Add( int item)
{
  _logger.log(String.Format( "{0} Add called with param {1}", DateTime.Now, item.ToString());
  _collection.Add(item);
  _logger.log(String.Format( "{0} Add completed with param {1}", DateTime.Now, item.ToString());
}

Leave a Comment