Created
April 28, 2015 07:41
-
-
Save yutaono/7c8297ce08c63878973b to your computer and use it in GitHub Desktop.
stackable trait pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// stackable trait pattern | |
// http://www.artima.com/scalazine/articles/stackable_trait_pattern.html | |
abstract class IntQueue { | |
def get: Int | |
def put(x: Int) | |
} | |
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 | |
} | |
trait Doubling extends IntQueue { | |
abstract override def put(x: Int) = super.put(x * 2) | |
} | |
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment