• Post Reply Bookmark Topic Watch Topic
  • New Topic

Adapter/Decorator Design Pattern  RSS feed

 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose you have been given the following requirements:
Given an API, you must modify its behaviour such that all non-private methods of all non-private classes print to stdout the text, "foo " followed by the current class name (this.getClass()). The behaviour must not be modified by altering the original source files. The modifications must be transparent to client classes.
Given the requirement for transparency, this suggests the use of inheritance and thus rules out the use of the Adapter Design Pattern.
Two possibilities are simple inheritance, or the Decorator Design Pattern. Whichever approach is chosen, the following problem exists.
Given two classes from the API:

The solution for the class B is relatively trivial:

A problem arises for the class A.
The method m() is straight forward:

The method m2() must return an instance of SubB that "looks like" (holds the same state) as the return value from the super.m2().
I am speculating with a reasonable level of certainty that this is not the first time that this kind of problem has encountered.
I am curious of how this problem may have been solved before, or how others might approach this problem.
I have two possible solutions:
- Manually copy the state data from the instance of B to the instance of SubB (using accessor/setter methods) which is not preferable
- Copy the state data in a homogeneous fashion using reflection:

If anyone has any suggestions or comments, I'd appreciate hearing them.
Thanks.
 
Jeff Langr
author
Ranch Hand
Posts: 799
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If this isn't just an exercise but something you really have to do, AspectJ is tailored for doing this sort of thing...
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I investigated AspectJ.
It seems that it requires the source code of the original API.
I should have clarified that, although I provided source in the example, I only have access to the binary class files*
I don't believe (from what I have read) that AspectJ can assist if this is the case.
*Note that this is not a licencing issue, but an internal issue.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Under what condition are these classes to start printing this foo?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!