52.scala程式設計思想筆記——多态
歡迎轉載,轉載請标明出處:http://blog.csdn.net/notbaron/article/details/50447604
源碼下載下傳連接配接請見第一篇筆記。
多态表示許多形态。
表示在不同類型上執行相同的操作。
基類和特征除了用于組裝類之外,還有很多其他用途。
例如,如果使用類A、特征B和特征C來建立新類,就可以選擇将這個新類隻當做A、B或C來處理。
例如,如果想建立一個遊戲,每個遊戲元素基于在遊戲世界中的位置将自身繪制在螢幕上,并且當兩個元素靠近時候,會進行互動。代碼如下:
import com.atomicscala.AtomicTest._
import com.atomicscala.Name
class Element extends Name {
definteract(other:Element) =
s"$this interact $other"
}
class Inert extends Element
class Wall extends Inert
trait Material {
defresilience:String
trait Wood extends Material {
defresilience = "Breakable"
trait Rock extends Material {
defresilience = "Hard"
class RockWall extends Wall with Rock
class WoodWall extends Wall with Wood
trait Skill
trait Fighting extends Skill {
def fight ="Fight!"
trait Digging extends Skill {
def dig ="Dig!"
trait Magic extends Skill {
def castSpell= "Spell!"
trait Flight extends Skill {
def fly ="Fly!"
class Character(var player:String="None")
extendsElement
class Fairy extends Character with Magic
class Viking extends Character
with Fighting
class Dwarf extends Character with Digging
class Wizard extends Character with Magic
class Dragon extends Character with Magic
with Flight
val d = new Dragon
d.player = "Puff"
d.interact(new Wall) is
"Dragon interact Wall"
def battle(fighter:Fighting) =
s"$fighter, ${fighter.fight}"
battle(new Viking) is "Viking, Fight!"
battle(new Dwarf) is "Dwarf, Fight!"
battle(new Fairy with Fighting) is
"anon, Fight!"
def fly(flyer:Element with Flight,
opponent:Element) =
s"$flyer, ${flyer.fly}, " +
s"${opponent.interact(flyer)}"
fly(d, new Fairy) is
"Dragon, Fly!, Fairy interact Dragon"
到目前為止,已經實作了如何建立基類,以及在繼承過程中添加新的方法,或者使用特征來混合新的功能。
不要假設一開始就可以做出正确的設計。
要不斷的重構代碼,直至設計方案看起來正确為止。不要滿足于“代碼可以工作即可”這種低标準。