Strategy Pattern help needed
There exists interface Algorithm
There exists class MathAlgorythm implements Algorithm
(returns MathResult, which implements Result
)
There exists class ChemitryAlgorythm implements Algorithm
(returns ChemitryResult, which implements Result
)
Additionally, there exists开发者_如何学Python a Context class
, which is used to pass data to these Algos. Data is passed in the following manner:
public Result executeStrategy(Data data) {
return algo.execute(data);
}
Suppose I, executeStrategy and get back
return MathAlgorithm.execute(data);
I get something of type Result right?
I then execute
return ChemitryAlgorithm.execute(data);
Again i get something Result
Question: Result is an interface. I need to gain access to concrete class implementation as MathResult or ChemistryResult. In other words. Once i get something of type Result, i need to dig deeper and know what class hides behind the interface
I hope this rambling is not too confusing.
Thank you for reading and responding
If you give Result
a method like T get()
which the concrete implementations have to implement, then you don't need to know about the concrete implementations.
Not sure if I understood your question but to know the concrete class of an instance you can use getClass() or alternatively use instanceof to check if it is MathResult etc. Be careful that you dont defeat the whole point of implementing the Result interface.
Make sure your Result interface is strong enough to satisfy all clients. That's the key so that you don't break polymorphic transparency.
If you really, really, REALLY need to know the concrete type, you can either use getClass, some sort of unique ID and a getter, or (most preferably) absorb the behavior into an operation of a concrete Result class.
How about:
interface Algorithm<R extends Result, D extends Data> {
T execute data(D data);
}
and then your MathAlgorithm implementation would look like this:
class MathAlgorithm implements Algorithm<MathResult, MathData> {
public MathResult execute(MathData data) {
// do whatever
return <instance of MathResult>;
}
}
the usage:
MathResult mathResult = new MathAlgorithm().execute(someMathData);
精彩评论