Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorate a decorator

After having implemented the decorator pattern and coded a couple decorators I noticed that the API allows a user to stack incompatible decorators. Is this a natural constraint of the pattern that the API designer should live with, or a wrongful implementation of the pattern by my part?

For example imagine there is a class that may be decorated with a binary decorator that encodes data in binary, or a string decorator that encodes data in a string. Given that string decorator was used, it may be further decorated with a JSON or XML decorator. Now it is evident that after having applied the JSON decorator it would be incompatible to use the XML decorator on top of it, or if the binary decorator was used the XML/JSON decorator are of no use.

Java example using the java.io package:

InputStream is = someInputStream;
BufferedInputStream bis = new BufferedInputStream(is);
ObjectInputStream ois = new ObjectInputStream(bis);
DataInputStream dis = new DataInputStream(ois);

The outcome of this is undefined but the API allows it.

like image 669
yannisf Avatar asked Nov 05 '22 21:11

yannisf


1 Answers

Decorators make easy to combine functionality. Whether the combined functionality makes any sense is up to the API user.

like image 119
gpeche Avatar answered Nov 12 '22 12:11

gpeche