动作 eat: aCookie super eat: aCookie. self colour: #green nag | item | [self isAwake] whileTrue: [item := self askForCookie. (self isCookie: item) ifTrue: [self eat: item] ifFalse: [self complainAbout: item]. (self isFull) ifTrue: [self sleep]] sleep self state: #asleep. self hunger: 0 wakeUp self tummy: Bag new. self state: #awake. self hunger: (Random new next * 13). "Cookie Monsters are superstitious and never eat more than 13 cookies in one go !" self nag
查询 isAsleep ^ state = #asleep isAwake ^ self isAsleep not isFull self isEmpty ifFalse: [^ self tummy size >= self hunger] ifTrue: [^false]
访问 hunger ^ hunger hunger: anIntegerNumberOfCookies hunger := anIntegerNumberOfCookies state ^ state state: aSymbol state := aSymbol
初始化 initialize self state: #asleep. self hunger: nil. super initialize
要确保正确的初始化,Monster creation 类方法也被重写。
建立 new ^ super new initialize
你将会注意到多数消息非常短。实际上,它们中的很大一部分由一行代码组成,返回 (^)或赋值(:=) 一些变量。这对于面向对象程序特别是 Smalltalk代码是典型的,因为所有访问到变量的有效模式必须被明确定义。出于可靠性的利益,许多状态变量不应该从一个对象的外部是可访问的。Smalltalk的编程环境便利了它的对到变量的任何访问都要求明确的方法定义的方式。因为浏览器允许快速的只用几下鼠标点击就定义这样的选择子,修改一个现存的方法,这么做不是特别烦人 -并且对程序的可靠性有利。以传统的方式列出这样的方法将使代码非常混乱,但是浏览器简化了这种冗长的文档。
注意从浏览器的类分类窗格上附着的按钮菜单上选择“fileOut”来保存在选择的类中的所有这些类定义到一个文本文件(在当前目录中),它们可以从一个文件列表“读回”到 Squeak(重编译每个定义)。

(页面上次更新: June 22, 1998)
smalltalk.zip
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-28676-9.html
明天我就叫几个兄弟去你家提亲
这才叫牢记历史
去年买盒感康13今年18