Java – proxy mode and rewriting
Suppose there is an interface subject
interface Subject { void request(); }
We have a realsubject class Suppose we want to enhance realsubject, we can use the proxy mode that wraps realsubject:
class Proxy implements Subject { private RealSubject ref; void request(){ ... } }
Or we can extend realsubject and override the method
class EnhancedSubject extends RealSubject { @Override void request() { ... } }
Which method is better? I know the Liskov principle; Let's assume that the enhanced subject satisfies the Liskov principle Are you still thinking about inheriting?
If there is no interface subject (that is, realsubject does not implement any interface), it seems that "inherit and override" is the only option, because there is no interface to implement in proxy mode If there is no theme interface, can you still apply proxy mode?
Solution
When answering your first question, "which method is better"?
I personally prefer to implement such things using interface and proxy (or decorator) patterns (see: item 16: favor combination rather than inheritance of effective Java (2nd Edition))
If the realsubject is not under your control, that is, in the same package, and is specially designed and recorded for extension, any implementation change from implementation to version may destroy the implementation of the subclass (enhanced subject) Basically, what I'm saying is that it leads to fragile code directly according to the specific implementation
When answering your second question, "if the enhanced subject satisfies the Liskov principle, will you still consider inheritance?"
If realsubject and enhancedsubject are under your control and released in the same life cycle, it is safe to use inheritance again, but it will lead to fragile code directly according to the specific implementation
Another thing I hope you can do with the interface is unit testing
For example, if you want to apply unit testing, it will be easier to inject the simulation dependency of realsubject into the proxy implementation of subject, so that you can specifically test the proxy class without completely testing the whole object hierarchy. Realsubject and enhancedsubject are just to confirm that the behavior of enhancedsubject meets the expectations
I think it can be said that if it is a very simple API and will hardly change in the future, the specific implementation will be simpler And keeping it simple and stupid (K.I.S.S.) is one of the best policies
"If there is no theme interface, can you still apply for agent mode?" You can inject realsubject into another class and use realsubject internally, but if the API using realsubject directly depends on a specific class, you have no other choice but to use inheritance