Skip to content

Instantly share code, notes, and snippets.

@nuttycom
Forked from darkfrog26/Element.scala
Created October 24, 2012 17:44
Show Gist options
  • Save nuttycom/3947613 to your computer and use it in GitHub Desktop.
Save nuttycom/3947613 to your computer and use it in GitHub Desktop.
package test
import collection.mutable.ListBuffer
/**
* @author Matt Hicks <mhicks@powerscala.org>
*/
trait Element
trait Parentable extends Element {
type P <: Element
}
trait Childable extends Element {
type C <: Element
}
trait SingleParent extends Parentable {
def parent: P
}
trait MultiParent extends Parentable {
def parents: Seq[P]
}
trait SingleChild extends Childable {
def child: C
}
trait MultiChild extends Childable {
def children: Seq[C]
}
trait MutableSingleChild extends SingleChild {
protected var _child: C = _
def child = _child
protected def assignChild(child: C) = synchronized {
_child = child
}
}
trait MutableMultiChild extends MultiChild {
protected val _children = new ListBuffer[C]
def children: Seq[C] = _children
protected def addChild(child: C) = synchronized {
_children += child
}
}
trait MutableSingleParent extends SingleParent {
protected var _parent: P = _
def parent = _parent
protected def assignParent(parent: P) = _parent = parent
}
trait MutableMultiParent extends MultiParent {
protected val _parents = new ListBuffer[P]
def parents: Seq[P] = _parents
protected def addParent(parent: P) = synchronized {
_parents += parent
}
}
class Example(name: String) extends MutableSingleParent with MutableMultiChild {
override type P = Example
override type C = Example
def +=(child: C) = {
addChild(child)
child.assignParent(this)
}
override def toString = "Example(name = %s, parent = %s)".format(name, parent)
}
object Example {
def main(args: Array[String]): Unit = {
val p = new Example("Parent")
val c1 = new Example("Child1")
val c2 = new Example("Child2")
p += c1
p += c2
p.children.foreach(println)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment