开发者

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 th开发者_高级运维at 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.


Java's IO classes appear to be a case of violating one or more OO design principles, such as Interface Segregation Principle and Liskov Substitution Principle, and abusing implementation inheritance. If ObjectInputStream and DataInputStream would not inherit from InputStream, then they could have only those methods which are allowed to be used on them. Code reuse through implementation inheritance is probably what has caused this problem - it could have been avoided by favoring composition over inheritance.


This sort of constraint enforcement is not part of the decorator pattern as I know it, but there is no reason why it couldn't be done. It is a tradeoff between simplicity of the API and security (from programmer mistakes).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜