zoukankan      html  css  js  c++  java
  • 2020.02.08

    模拟图形绘制

    对于一个图形绘制程序,用下面的层次对各种实体进行抽象。定义一个 Drawable 的特 质,其包括一个 draw 方法,默认实现为输出对象的字符串表示。定义一个 Point 类表示点, 其混入了 Drawable 特质,并包含一个 shift 方法,用于移动点。所有图形实体的抽象类为

    Shape,其构造函数包括一个 Point 类型,表示图形的具体位置(具体意义对不同的具体图 形不一样)。Shape 类有一个具体方法 moveTo 和一个抽象方法 zoom,其中 moveTo 将图形从 当前位置移动到新的位置, 各种具体图形的 moveTo 可能会有不一样的地方。zoom 方法实 现对图形的放缩,接受一个浮点型的放缩倍数参数,不同具体图形放缩实现不一样。继承 Shape 类的具体图形类型包括直线类 Line 和圆类 Circle。Line 类的第一个参数表示其位置, 第二个参数表示另一个端点,Line 放缩的时候,其中点位置不变,长度按倍数放缩(注意, 缩放时,其两个端点信息也改变了),另外,Line 的 move 行为影响了另一个端点,需要对 move 方法进行重载。Circle 类第一个参数表示其圆心,也是其位置,另一个参数表示其半 径,Circle 缩放的时候,位置参数不变,半径按倍数缩放。另外直线类 Line 和圆类 Circle 都混入了 Drawable 特质,要求对 draw 进行重载实现,其中类 Line 的 draw 输出的信息样式 为“Line:第一个端点的坐标--第二个端点的坐标)”,类 Circle 的 draw 输出的信息样式为 “Circle center:圆心坐标,R=半径”。如下的代码已经给出了 Drawable 和 Point 的定义, 同时也给出了程序入口 main 函数的实现,请完成 Shape 类、Line 类和 Circle 类的定义。

    case class Point(var x:Double,var y:Double) extends Drawable{
      def shift(deltaX:Double,deltaY:Double){x+=deltaX;y+=deltaY}
    }
    trait Drawable{
    def draw(){
      println(this.toString)
      }
    }
     
    abstract class Shape extends Drawable{
      def moveTo(point:Point)
      def zoom(multiple:Double)
      def draw()
    }
     
    class Line(var point1:Point,var point2:Point) extends Shape{
      def zoom(multiple:Double){
        val x = (point1.x + point2.x)/2
        val y = (point1.y + point2.y)/2
        point1.x = (point1.x - x)*multiple
        point1.y = (point1.y - y)*multiple
        point2.x = (point2.x - x)*multiple
        point2.y = (point2.y - y)*multiple
      }
    def moveTo(point:Point){
        val changex = point1.x-point.x
        val changey = point1.y-point.y
        point1.x = point.x
        point2.y = point.y
        point2.x = point2.x - changex
        point2.y = point2.y - changey
      }
      override def draw(){
        println("Line:("+point1.x+","+point1.y+")--("+point2.x+","+point2.y+")")
      }
    }
     
    class Circle(var point:Point,var R:Double) extends Shape{
      def zoom(multiple:Double){
        R = R*multiple
      }
      def moveTo(point:Point){
        this.point.x = point.x
        this.point.y = point.y
      }
      override def draw(){
        println("Circle center:("+point.x+","+point.y+"),R="+R)
        }
    }
     
    object exercise
    {
     def main(args: Array[String]) {
        val p=new Point(10,30)
        p.draw
        val line1 = new Line(Point(0,0),Point(20,20))
        line1.draw
        line1.moveTo(Point(5,5)) 
        line1.draw
        line1.zoom(2)
        line1.draw
        val cir= new Circle(Point(10,10),5)
        cir.draw
        cir.moveTo(Point(30,20))
        cir.draw
        cir.zoom(0.5)
        cir.draw
     } 
    }

  • 相关阅读:
    Java设计模式——单例模式
    Java设计模式——工厂模式
    多线程
    Collection集合
    内部类
    多态
    接口
    面向对象(2)
    数组
    面向对象(1)
  • 原文地址:https://www.cnblogs.com/zql98/p/12283780.html
Copyright © 2011-2022 走看看