存在接口算法
存在类MathAlgorythm实现算法
(返回MathResult,它实现Result
)
存在类ChemitryAlgorythm实现算法
code> (返回 ChemitryResult,它实现 Result
)
此外,还存在一个 Context 类
,用于将数据传递给这些 Algo。数据的传递方式如下:
public Result executeStrategy(Data data) {
return algo.execute(data);
}
假设我,executeStrategy并返回
return MathAlgorithm.execute(data);
我得到了 Result 类型的内容,对吗?
然后我执行
return ChemitryAlgorithm.execute(data);
我再次得到一些结果
问题:
结果是一个界面。我需要访问作为 MathResult 或 ChemistryResult 的具体类实现。换句话说。一旦我得到 Result 类型的东西,我需要更深入地挖掘并知道接口后面隐藏了什么类,
我希望这个漫无目的的内容不会太令人困惑。
感谢您的阅读和回复
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 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
发布评论
评论(4)
如果你给
Result
一个像T get()
这样具体实现必须实现的方法,那么你不需要了解具体实现。If you give
Result
a method likeT get()
which the concrete implementations have to implement, then you don't need to know about the concrete implementations.不确定我是否理解你的问题,但要知道实例的具体类,你可以使用 getClass() 或使用 instanceof 来检查它是否是 MathResult 等。请小心,不要破坏实现 Result 接口的全部要点。
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.
确保您的结果界面足够强大,足以满足所有客户。这是不破坏多态透明度的关键。
如果你真的,真的,真的需要知道具体类型,你可以使用 getClass,某种唯一的 ID 和 getter,或者(最好)吸收行为转化为具体 Result 类的操作。
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.
怎么样:
然后你的 MathAlgorithm 实现将如下所示:
用法:
How about:
and then your MathAlgorithm implementation would look like this:
the usage: