I get several objects of type Foo from a call to an external API. Locally I want to process those objects with a little added information so I have a subclass FooSon that adds those extra fields. How can I convert all those objects I get,开发者_如何学C to my new inherited type? Downcasting doesn't seem to be an option because those objects aren't really FooSon.
The only solution I have come up with is creating a convert function that takes the Foo object as an argument and then copies all public/protected values to a new FooSon object that is then returned.
The disadvantages are:
- Loosing information (private values)
- Having to adapt the convert function if Foo is ever changed.
Class Foo doesn't implement a copy constructor or clone operator. I have the Foo source code but I would like to avoid changing it in order to keep compatibility with future releases. Nevertheless if it is the only viable alternative I would change the Foo implementation to get what I need.
FooSon could have a field in it that is a Foo. then just assign the returned value into that field. You could then create methods in Fooson that delegate their calls to the Foo field for the information that you need from the Foo from outside.
I think decorator pattern should works here:
class Foo implements FooApi {...}
class FooSon implements FooApi {
private FooApi decoratedFoo;
private String additional;
public FooSon(FooApi decoratedFoo) {
this.decoratedFoo = decoratedFoo;
}
...
}
but you can do this only if you have interface for your Foo object.
Maybe I haven't fully understood the problem, but why instead of subclassing Foo (inheritance) aren't you storing Foo like a field type in FooSon (composition)?
In anycase, if you can't modify access control to Foo type because the objects are defined into an external library, you can't get direct access to private fields(this is exactly the property of a private field). If those private fields can be accessed from getters and setters method, so wrap that methods in your FooSon class.
Well, as you already found out down casting is not applicable in this situation. I see the following options:
The external library provides some factory mechanism you could use to make it instantiate
FooSon
insteadFoo
.The recipient wraps
Foo
objects inFooSon
objects, possibly using the delegator pattern.The recipient logically attaches additional information by to
Foo
objects by using a map withFoo
as key.
You should not downcast, you have no guarantee it will succeed and there are better ways of dealing with this problem. For one you could wrapper the Foo object in another class and delegate the appropriate method calls back to the Foo object.
I suggest you take some time to make sure you understand some basic OO concepts. In particular, google for "composition versus inheritance", this link seems like a decent explanation.
精彩评论