1.什么是访问模式
以我的理解就是不同模型提供不同的行为,而重点就在于判决不同的模型,这里我们就是通过访问的模式
2.普通风格
---------继承实现抽象的技术来达到"访问模式"而产生不同行为
package shapes {
case class Point(x: Double, y: Double)
abstract class Shape() {
def draw(): Unit
}
case class Circle(center: Point, radius: Double) extends Shape() {
def draw() = println("Circle.draw: " + this)
}
case class Rectangle(lowerLeft: Point, height: Double, width: Double) extends Shape() {
def draw() = println("Rectangle.draw: " + this)
}
case class Triangle(point1: Point, point2: Point, point3: Point)extends Shape() {
def draw() = println("Triangle.draw: " + this)
}
}
每个类都具体化了其中的行为,这种是耦合度太低了,不利于源码二次维护
3.另一种提供原本类供外界本类当作"辨别的对象",目的是最大耦合
package shapes {
trait ShapeVisitor {
def visit(circle: Circle): Unit
def visit(rect: Rectangle): Unit
def visit(tri: Triangle): Unit
}
case class Point(x: Double, y: Double)
sealed abstract class Shape() {
def accept(visitor: ShapeVisitor): Unit
}
case class Circle(center: Point, radius: Double) extends Shape() {
def accept(visitor: ShapeVisitor) = visitor.visit(this)
}
case class Rectangle(lowerLeft: Point, height: Double, width: Double)
extends Shape() {
def accept(visitor: ShapeVisitor) = visitor.visit(this)
}
case class Triangle(point1: Point, point2: Point, point3: Point)
extends Shape() {
def accept(visitor: ShapeVisitor) = visitor.visit(this)
}
}
行为:
package shapes {
class ShapeDrawingVisitor extends ShapeVisitor {
def visit(circle: Circle): Unit =
println("Circle.draw: " + circle)
def visit(rect: Rectangle): Unit =println("Rectangle.draw: " + rect)
def visit(tri: Triangle): Unit =println("Triangle.draw: " + tri)
}
}
这种风格就跟上面的很不一样,不同的类产生不同的行为,而该行为分离了本类的主题,实现了耦合,在trait ShapeVisitor中处理三个行为,这就很容易去维护code了,主要对分离的行为进行维护即可,这样不会修改主体
缺点:违背了
OpenClosed Principle
我们都把对象提供给人家(即行为)了-----!不安全
4.比较安全的做法
package shapes2 {
case class Point(x: Double, y: Double)
sealed abstract class Shape()
case class Circle(center: Point, radius: Double) extends Shape()
case class Rectangle(lowerLeft: Point, height: Double, width: Double) extends Shape()
case class Triangle(point1: Point, point2: Point, point3: Point) extends Shape()
}
package shapes2 {
class ShapeDrawer(val shape: Shape) {
def draw = shape match {
case c: Circle => println("Circle.draw: " + c)
case r: Rectangle => println("Rectangle.draw: " + r)
case t: Triangle => println("Triangle.draw: " + t)
}
}
object ShapeDrawer {
implicit def shape2ShapeDrawer(shape: Shape) = new ShapeDrawer(shape)
}
}
我们通过巧妙的方法实现了耦合度
不像上个方法那样把this直接送给行为,这样是主动暴露的行为,而这里是根据不同对象做出不同的行为---是属于被动暴露的的行为