Scala 中的复合设计模式?
在java中,我可以实现复合设计模式,如下所示:
interface Component{
void operation();
}
class Composite implements Component{
@override
public void operation(){
for(Child child in children){
child.operation();
}
}
public void add(Component child){//implementation}
public void remove(Component child){//implementation}
public void getChild(int index);
}
class Leaf implements Component{
@override
public void operation(){
//implementation
}
}
如何在scala中编写它?特别是我无法理解如何编写接口并实现它?
In java I can implement the composite design pattern as follows:
interface Component{
void operation();
}
class Composite implements Component{
@override
public void operation(){
for(Child child in children){
child.operation();
}
}
public void add(Component child){//implementation}
public void remove(Component child){//implementation}
public void getChild(int index);
}
class Leaf implements Component{
@override
public void operation(){
//implementation
}
}
How can I write it in scala? In particular I am having trouble understanding how to write an interface and implement it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Scala 中,没有任何具体方法的 Trait 只是一个接口。所以直接翻译是:
虽然如果你想要更惯用的 Scala,我会推荐这样的东西作为
Composite
的定义:用作:
如果你想得出一个合乎逻辑的结论,我建议将整个复合结构构建为不可变的有向无环图(尽管我意识到这通常是不可能的):
In Scala, a Trait without any concrete methods is just an interface. So a direct translation would be:
Though if you want more idiomatic Scala, I'd recommend something like this as a definition for
Composite
:To be used as:
If you want to take this to a logical conclusion, I'd advocate building the whole composite structure as an immutable Directed Acyclic Graph (though I appreciate that this often isn't possible):
这
是一个非常直接的翻译。在 Scala 中,通常首选不可变的解决方案。另一个区别是,您经常使用模式匹配而不是继承。例如,您可以通过从
Component
和Leaf
中删除operation()
并改为编写来重写示例Something like
This is a very direct translation. Often an immutable solution is preferred in Scala. Another difference is, that you often use pattern matching instead of inheritance. E.g. you could rewrite the example by removing
operation()
fromComponent
andLeaf
and writing instead更干净的不可变方式是:
A cleaner immutable way would be:
在 Java 中作为接口呈现的功能可以在 Scala 中编码为特征
值得一提的是,特征比 Java 接口更强大,并且可以包括实现和接口规范。
Functionality presented in Java as an interface can be coded in Scala as a trait
It's worth saying that traits are more powerful than Java interfaces, and can include implementation as well as interface specifications.