Java Decorating The Easy Way
Say you have an API that is not accessible to change:
List<LegacyObject> getImportantThingFromDatabase(Criteria c);
Imaging Legacy Object has a ton of fields and you want to extend it to make getting at certain information easier:
class ImprovedLegacyObject extends LegacyObject {
String getSom开发者_如何学JAVAeFieldThatUsuallyRequiresIteratorsAndAllSortsOfCrap() {
//cool code that makes things easier goes here
}
}
However, you can't just cast to your ImprovedLegacyObject
, even though the fields are all the same and you haven't changed any of the underlying code, you've only added to it so that code that uses LegacyObject
still works, but new code is easier to write.
Is it possible to have some easy way to convert LegacyObject
to ImprovedLegacyObject
without recreating all of the fields, or accessors? It should be a fast opperation too, I konw you could perform something by using reflections to copy all properties, but I don't think that would be fast enough when doing so to masses of LegacyObjects
EDIT: Is there anything you could do with static methods? To decorate an existing object?
You would have to perform the copying yourself. You can either have a constructor that does this (called a copy constructor):
public ImprovedLegacyObject(LegacyObject legacyObject) {
...
//copy stuff over
this.someField = legacyObject.getSomeField();
this.anotherField = legacyObject.getAnotherField();
...
}
or you can have a static factory method that returns an ImprovedLegacyObject
public static ImprovedLegacyObject create(LegacyObject legacyObject) {
...
//copy stuff over
...
return improvedLegacyObject;
}
If you're planning on extending this behavior to other legacy objects, then you should create an interface
public interface CoolNewCodeInterface {
public String getSomeFieldThatUsuallyRequiresIteratorsAndAllSortsOfCrap() {
}
public String getSomeFieldInAReallyCoolWay() {
}
}
Then your ImprovedLegacyObject
would look like this:
public ImprovedLegacyObject extends LegacyObject implements CoolNewCodeInterface {
//implement methods from interface
}
How about making a copy constructor for your Improved Legacy Object that takes a Legacy Object as an argument. Then just create new objects from the old ones.
精彩评论