1. 程式人生 > >Scala練習十

Scala練習十

\1. java.awt.Rectangle類有兩個很有用的方法translate和grow,但可惜的是像java.awt.geom.Ellipse2D這樣的類沒有。在Scala中,你可以解決掉這個問題。定義一個RenctangleLike特質,加入具體的translate和grow方法。提供任何你需要用來實現的抽象方法,以便你可以像如下程式碼這樣混入該特質:

1
2
3
val egg = new java.awt.geom.Ellipse2D.Double(5,10,20,30) with RectangleLike
egg.translate(10,-10)
egg.grow(10,20)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.awt.geom.Ellipse2D

trait RectangleLike {
  this: Ellipse2D.Double =>
  def translate(x: Double, y: Double) {
    this.x = x
    this.y = y
  } 

  def grow(x: Double, y: Double) {
    this.x += x
    this.y += y
  }
}

object EclipseTest extends App {
  val egg = new java.awt.geom.Ellipse2D.Double(5
,10,20,30) with RectangleLike egg.translate(10,-10) egg.grow(10,20) println(egg.getX) println(egg.getY) }

\2. 通過把scala.math.Ordered[Point]混入java.awt.Point的方式,定義OrderedPoint類。按辭典編輯方式排序,也就是說,如果x\<x’或者x=x’且y\<y’則(x,y)\<(x’,y’)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class OrderedPoint
(x : Int, y : Int) extends java.awt.Point(x, y) with scala.math.Ordered[OrderedPoint]
{ def compare(that : OrderedPoint) : Int = { if (this.x == that.x && this.y == that.y) { 0 } else if ((this.x < that.x || this.x == that.x) && this.y < that.y) { -1 } else { 1 } } } object TestTrait extends App { val test = Array(new OrderedPoint(3, 4), new OrderedPoint(4, 5)); scala.util.Sorting.quickSort(test) test.foreach((p : OrderedPoint) => {println(p)}) val p1 = new OrderedPoint(3, 4); val p2 = new OrderedPoint(4, 5); println(p2 > p1) }

\3. 檢視BitSet類,將它的所有超類和特質繪製成一張圖。忽略型別引數([…]中的所有內容)。然後給出該特質的線性化規格說明

\4. 提供一個CryptoLogger類,將日誌訊息以凱撒密碼加密。預設情況下密匙為3,不過使用者也可以重寫它。提供預設密匙和-3作為密匙是的使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
trait Logger {
  def log(str: String, key: Int = 3) : String
}

class CryptoLogger extends Logger {
  def log(str: String, key: Int) : String = {
    for ( i <- str) yield if (key >= 0) (97 + ((i - 97 + key)%26)).toChar else (97 + ((i - 97 + 26 + key)%26)).toChar
  }
}    

object CryptoLoggerTest extends App {
  val text = "nmred"
  println(text)
  println(new CryptoLogger().log(text))
  println(new CryptoLogger().log(text, -3))
}

\5. JavaBean規範裡有一種提法叫做屬性變更監聽器(property change listener),這是bean用來通知其屬性變更的標準方式。PropertyChangeSupport類對於任何想要支援屬性變更通知其屬性變更監聽器的bean而言是個便捷的超類。但可惜已有其他超類的類—比如JComponent—必須重新實現相應的方法。將PropertyChangeSupport重新實現為一個特質,然後將它混入到java.awt.Point類中

1
2
3
4
5
6
import java.awt.Point
import java.beans.PropertyChangeSupport

trait PropertyChange extends PropertyChangeSupport

val p = new Point() with PropertyChange