您的位置:首页 > 编程语言

52.scala编程思想笔记——多态

2016-01-02 09:38 274 查看
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

with Fighting

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"

到目前为止,已经实现了如何创建基类,以及在继承过程中添加新的方法,或者使用特征来混合新的功能。

不要假设一开始就可以做出正确的设计。

要不断的重构代码,直至设计方案看起来正确为止。不要满足于“代码可以工作即可”这种低标准。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: