[英]Bad sides of Scala Cake Pattern as dependencies injection
Let's see the following very simple cake pattern example:让我们看看以下非常简单的蛋糕图案示例:
trait PrintSomething{
def printSomeThing(s:String):Unit
}
trait PrintSomethingToConsole extends PrintSomething{
override def printSomeThing(s: String): Unit = println("Print To Console!!!")
}
trait PrintSomethingToLog extends PrintSomething{
override def printSomeThing(s: String): Unit = println("Print To Log!!!")
}
class MyAction{
self:PrintSomething =>
printSomeThing("This is it")
}
new MyAction with PrintSomethingToConsole
new MyAction with PrintSomethingToLog
I see in some blogs that the bad side of this pattern is breaking Open-Close Principle
and Interface Segregation Principle
.我在一些博客中看到,这种模式的坏处是违反Open-Close Principle
和Interface Segregation Principle
。
As far as I understand, there is a possibility to override printSomething
method inside MyAction and modify functionality with no matter which PrintSomething
trait was injected:据我了解,无论注入哪个PrintSomething
特性,都可以覆盖 MyAction 中的printSomething
方法并修改功能:
class MyAction{
self:PrintSomething =>
override def printSomeThing(s: String): Unit = println("I just Broke Open-Close Principle!!!!! ")
}
Am I right?我对吗?
However I don't understand how I can violate Interface Segregation Principle
here.但是我不明白我怎么会在这里违反Interface Segregation Principle
。 Can someone elaborate?有人可以详细说明吗?
I don't see any conflict with the open-closed principle.我看不出与开闭原则有任何冲突。 All your classes and traits are open for extension and closed for modification.您所有的类和特征都对扩展开放,对修改关闭。 And since they only have a single method, the interface segregation principle doesn't really apply!而且由于它们只有一个方法,因此接口隔离原则并不真正适用!
Even if you override printSomeThing
in your MyAction
class, you have still not violated either principle.即使您在MyAction
类中覆盖了printSomeThing
,您仍然没有违反任何一个原则。 All the objects remain open for extension (you can extend them) and closed for modification (you can not change their behaviour).所有对象都保持开放以进行扩展(您可以扩展它们)并关闭以进行修改(您不能改变它们的行为)。 An instance of PrintSomethingToLog
will always print to the log; PrintSomethingToLog
的实例将始终打印到日志; you cannot modify it to print to the console.您不能修改它以打印到控制台。
An instance of PrintSomething
may have different implementations of printSomeThing
but this is just polymorphism via inheritance; PrintSomething
的实例可能有不同的printSomeThing
实现,但这只是通过继承实现的多态性; it does not mean that PrintSomething
is open for modification because PrintSomething
is an interface, not a concrete class, and you can't change the interface.这并不意味着PrintSomething
可以修改,因为PrintSomething
是一个接口,而不是一个具体的类,并且您不能更改该接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.