views:

305

answers:

2

I've noticed that on all the examples that illustrate the decorator pattern, there is a base class/interface and there is a decorator class that inherits/implements it, after which, all the decorated classes extend the decorator class. Something along the following lines :

Interface Window > WindowDecorator > WindowDecorator > VerticalScrollBarDecorator

the above hierarchy was taken from Wikipedia's Design Pattern Page.

The thing is, I want decorate some "Operation" classes, and have something along the following hierarchy :

  • root class is Operation

  • decorated classes could be Operation1, Operation2, and so forth.

I would have a constructor taking an Operation object in my Operation class, like this :


public Operation(Operation op)
{
  this.op = op;
}

an abstract method ( let's call it doOperation ) that performs the operation ( and which each subclass overrides ) and another method that calls the "stored" object's doOperation, like this ( located in the base class ):


public void executeOperation(some_args_here)
{
  if(op != null)
    op.doOperation(); // call stored object's doOperation first
  doOperation(); //execute this operation
}

The thing is, I don't really see the need for a OperationDecorator class here, when I can do everything a OperationDecorator class would do right in the base class. Am I misusing the decorator pattern if I use it like this? Am I missing out on some of it's features?

+1  A: 

Well, first, you're not misusing anything, you are writing code. Don't be tempted to give it names, and artificially make it a pattern it is not.

Second of all, if the only thing you are doing is making a new object just so you can call your doOperation() with some arguments, then it can be considered a weird design.

There is no need to create an abstraction just for the sake of passing parameters.

In this case, if you insist on comparing to the Decorator pattern: yes, this is misuse.

Yuval A
+2  A: 

Decorator pattern is used to provide special features to the objects at runtime. (Assuming that the Objects already exists and new features need to be added in certain cases).

Hence, Decorator class implements and aggregate the existing Base class so that operations can be extended. The Base class will be left unchanged and DecoratorClass is used when special behavior is needed by giving the instance of BaseClass.

In your case, the methods names are different. The user of the Base class (who is unware of Decorated class) may get confused whether to use doOperation or executeOperation.

aJ
what if the doOperation is protected?
Geo
Then it is very clear right. User of Base class **does not** see the doOperation method. You can refer template method design pattern for this kind of making the method as protected and providing different implementation.
aJ