Groovy相当于Scala特性的可堆叠修改?
我一直在阅读Scala编程书籍(由Martin Odersky、Lex Spoon、Bill Venners ed1编写),发现了traits。我发现一个有趣的部分是可堆叠的修改。使用的示例是Groovy相当于Scala特性的可堆叠修改?,groovy,traits,Groovy,Traits,我一直在阅读Scala编程书籍(由Martin Odersky、Lex Spoon、Bill Venners ed1编写),发现了traits。我发现一个有趣的部分是可堆叠的修改。使用的示例是 abstract class IntQueue { def get(): Int def put(x: Int) } trait Incrementing extends IntQueue { abstract override def put(x: Int) {super.put(x+1)}
abstract class IntQueue {
def get(): Int
def put(x: Int)
}
trait Incrementing extends IntQueue {
abstract override def put(x: Int) {super.put(x+1)}
}
trait Filtering extends IntQueue{
abstract override def put(x: Int){
if(x >=0) super.put(x)
}
}
因此,提供的示例有一个具体的类“BasicIntQueue”,它扩展了IntQueue,如下所示
import scala.collection.mutable.ArrayBuffer
class BasicIntQueue extends IntQueue{
private val buf = new ArrayBuffer[Int]
def get() = buf.remove(0)
def put(x: Int) {buf +=x}
}
scala>val queue=(通过过滤递增的新基本队列)
scala>queue.put(-1);queue.put(0);queue.put(1)
scala>queue.get()=1
因此,该示例显示过滤和递增都是“链接”的,并在元素“放入”队列之前执行
我只是想知道如何在Groovy中实现这一点。可能因为Groovy的元编程能力而不需要它。Groovy没有一种自然的方式来实现可堆叠的特性。类别提供了一些特性功能,但它们不太适合重写方法,如果没有太多元类魔法,它们就无法堆叠 groovy中更好的方法是将装饰器模式与注释一起应用。每个“trait”都可以重写适当的行为并委托给“super”类。例如:
interface IntQueue {
def get()
def put(x)
}
class Incrementing implements IntQueue {
@Delegate IntQueue self
def put(x) {
self.put(x+1)
}
}
class Filtering implements IntQueue {
@Delegate IntQueue self
def put(x) {
if (x >= 0) {
self.put(x)
}
}
}
class BasicIntQueue implements IntQueue {
private buf = []
def get() { buf.pop() }
def put(x) { buf << x }
}
从Groovy支持和开始。因此,实现看起来与Scala完全相同:
interface IntQueue {
Integer get()
void put(Integer x)
}
trait Incrementing implements IntQueue {
void put(Integer x) { super.put(x+1) }
}
trait Filtering implements IntQueue {
void put(Integer x) { if(x >= 0) super.put(x) }
}
class BasicIntQueue implements IntQueue {
private buf = new ArrayList<Integer>()
Integer get() { buf.remove(0) }
void put(Integer x) { buf << x}
String toString() { buf.toString() }
}
def queue = new BasicIntQueue().withTraits Incrementing, Filtering
queue.put(-1)
queue.put(0)
queue.put(1)
assert queue.get() == 1
接口队列{
整数get()
无效put(整数x)
}
trait递增实现IntQueue{
void put(整数x){super.put(x+1)}
}
特征过滤实现了IntQueue{
void put(整数x){if(x>=0)super.put(x)}
}
类BasicIntQueue实现IntQueue{
private buf=new ArrayList()
整数get(){buf.remove(0)}
void put(Integer x){buf我考虑过decorator模式,但是以前没有@Delegate注释的经验。谢谢这个好例子。
interface IntQueue {
Integer get()
void put(Integer x)
}
trait Incrementing implements IntQueue {
void put(Integer x) { super.put(x+1) }
}
trait Filtering implements IntQueue {
void put(Integer x) { if(x >= 0) super.put(x) }
}
class BasicIntQueue implements IntQueue {
private buf = new ArrayList<Integer>()
Integer get() { buf.remove(0) }
void put(Integer x) { buf << x}
String toString() { buf.toString() }
}
def queue = new BasicIntQueue().withTraits Incrementing, Filtering
queue.put(-1)
queue.put(0)
queue.put(1)
assert queue.get() == 1