[英]How to check that I work with instance of subclass?
I read an interesting article on the third SOLID principle: https://stackify.com/solid-design-liskov-substitution-principle/我读了一篇关于第三个SOLID原则的有趣文章: https://stackify.com/solid-design-liskov-substitution-principle/
At the same time, I read that using an instanceof
operator can be a violation of the SOLID rule.同时,我读到使用
instanceof
运算符可能违反 SOLID 规则。 How to deal with the following problem.如何处理以下问题。
I have two classes (pseudo code):我有两个类(伪代码):
CoffeeMachine {
brewCoffee();
}
PremiumCoffeeMachine extends CoffeeMachine {
brewCoffee()
brewEspresso()
}
Then somewhere in the program I got a collection of coffee machines然后在程序的某个地方我收集了一些咖啡机
Set<CoffeeMachine> coffeeMachines
Now I'd like to make coffee with each of the coffee machines.现在我想用每台咖啡机煮咖啡。 How will I know I can make an espresso without using an
instanceof
operator?我怎么知道我可以在不使用
instanceof
运算符的情况下制作浓缩咖啡?
Maybe it's the only way, but I read many times today that an instanceof
operator breaks the SOLID也许这是唯一的方法,但我今天读了很多次,
instanceof
运算符破坏了 SOLID
Do you know an interesting article or can you provide a solution to such a problem?你知道一篇有趣的文章,或者你能提供一个解决这个问题的方法吗? Maybe II wrong and SOLID says that subclasses should't contains extra methods?
也许 II 错了,SOLID 说子类不应该包含额外的方法?
Your given reference gives a lot of insight on how you could deal with this problem.您给出的参考资料提供了很多关于如何处理这个问题的见解。
In the end, you want to iterate over a Collection
of CoffeeMachine
instances and instruct them to brew coffee, as described by brewCoffee()
.最后,您想要遍历
CoffeeMachine
实例的Collection
并指示它们冲泡咖啡,如brewCoffee()
所述。 And you are correct, to know if your machine is a premium one, you would have to use the instanceof
operator.你是对的,要知道你的机器是否是高级机器,你必须使用
instanceof
运算符。
If you want a more flexible solution, you could use the following design:如果您想要更灵活的解决方案,可以使用以下设计:
public interface CoffeeMachine {
// check if this machine supports a given selection
// if not, #brewCoffee should throw an exception
boolean supports(CoffeeSelection selection);
CoffeeDrink brewCoffee(CoffeeSelection selection);
}
Now, one could imagine a PremiumCoffeeMachine
that supports an EspressoCoffee
(a special CoffeeSelection
).现在,可以想象一个
PremiumCoffeeMachine
支持EspressoCoffee
(一种特殊的CoffeeSelection
)。 CoffeeSelection
ifself can be an interface
, a class
or an enum
, depending on the complexity and requirements of the different coffees. CoffeeSelection
ifself 可以是一个interface
,一个class
或一个enum
,这取决于不同咖啡的复杂性和要求。
instanceof doesn't break SOLID. instanceof 不会破坏 SOLID。 The idea that is being expressed on the link that you provided is that the contract for brewCoffee SHOULD NOT be stricter in the subclass, as this breaks the contract.
您提供的链接上表达的想法是 brewCoffee 的合同不应该在子类中更严格,因为这违反了合同。 And actually Java won't let you do this
实际上 Java 不会让你这样做
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.