首先我們先看看如果使用不使用 Trait 如何來實(shí)現(xiàn)這些類,首先我們定義一些基本的幾何圖形類如 Point 和Rectangle:
class Point(val x:Int, val y:Int)
class Rectangle(val topLeft:Point, val bottomRight:Point){
def left =topLeft.x
def right =bottomRight.x
def width=right-left
// and many more geometric methods
}
abstract class Component {
def topLeft :Point
def bottomRight:Point
def left =topLeft.x
def right =bottomRight.x
def width=right-left
// and many more geometric methods
}
trait Rectangular {
def topLeft:Point
def bottomRight:Point
def left =topLeft.x
def right =bottomRight.x
def width=right-left
// and many more geometric methods
}
然后我們修改 Component 類定義使其“融入”Rectangular 特性:
abstract class Component extends Rectangular{
//other methods
}
同樣我們也修改 Rectangle 定義:
class Rectangle(val topLeft:Point, val bottomRight:Point) extends Rectangular{
// other methods
}
更多建議: