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.
Decorators make easy to combine functionality. Whether the combined functionality makes any sense is up to the API user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With