久仰SmallTalk的大名,大概是因為很多design pattern的名著都提到它,并且一說到OOAD也都會提到它老人家。但是我并不知道它是啥子東東,就像誰關心Ada一樣。
但是出來混總是需要還的L沒想到Martin大叔的“分析模式”竟然是用這個鬼東西寫的代碼,額的神啊,我只好打起萬分的精神,惡補一下。
最不幸的是網上能夠找到的關于SmallTalk書,確實比Java少得多的多。找到一本E文的,將就吧。
另外的發現就是ruby號稱ruby>(smalltalk+perl),所以有些資料可以在ruby中找到哈。
我的這份Smalltalk的學習筆記,并不是按照Smalltalk進階的思路整理的,而是在閱讀AP第七章的過程中隨用到隨整理的。看AP是夠用了。
變量和賦值
字符 $a $1
字符串變量,用單引號表示。注意在SmallTalk中雙引號是注釋。所以
‘John’ ‘Martin’這是對的。
A := “John Hunt”這是錯的(去死? )
‘a’和$a表示的是不同類的實例,前者對應的Strings;后者對應的Charater。
Symbols
我覺得這就相當于java中的常量
#join week system42
賦值 := (這個和Delphi一樣哈)
myName := ‘John Hunt
newIndex := oldIndex
臨時變量
|x y z|
x :=5.
y :=6.
Z :=x+y.
Transcript show: z printString.
|
isKindof:類型判斷
(anObject isKindOf: String) ifTrue: [...] ifFalse: [...] is an example of Smalltalk's runtime equilivant of "type testing"
集合
Enumerating Collections
do – does the same operation on every element of the collection.
MyCollection do: [:piece | piece reset]
對MyCollection的每個element發送消息reset(其實就是執行reset)
collect – like do: but returns a collection of the results.
select – test every element and returns those which pass.
reject – test every element and returns those which fail.
detect – returns the first element which passes the test
inject:into
inject
在Smalltalk語言中也支持集合的迭代器,如果你要求Smalltalk程序員求數組元素的和,他們會像這樣來使用inject函數:
sumOfValues "Smalltalk method"
^self values
inject: 0
into: [ :sum :element | sum + element value]
|
inject是這樣工作的,當關聯的代碼塊第一次被調用時,sum被賦給inject的參數值(在這里是0),element取數組第一個元素。第二次和以后調用到代碼塊時,sum被賦給上次調用代碼塊時返回的值,這樣sum就跑完了全程,inject最終的結果是代碼塊最后被調用的值。
Dictionary
Dictionary是Set的子類。
at : aKey 對應Java的get(key)
at : aKey put : aValue對應Java的put(key, value)
應用方式:
Code Block
[ :params | <message-expressions> ]
Where :params is the list of parameters the code can take. This means that the Smalltalk code:
[:x | x + 1]可以理解為:f(x) = x + 1
Code Block的調用:
[:x | x + 1] value: 3
can be evaluated as
f(3) = 3 + 1
這是相等于Code Block的定義和調用在一起。
令一種方法是先定義code Block,然后在其它的地方再調用。
anotherBlock := [ :parml :parm2 | | temp |
temp := pannl incorporate: parm2.
temp rehash.
].
|
說明:
1) 定義Code Block,anotherBlock。
2) parml ,parm2是兩個參數
3) temp是定義的變量
調用:anotherBlock value: objecfcl value: object2
盡管狠不適應,但是Code Block可以使得代碼簡潔明了:
positiveAmounts := allAmounts select: [:amt | amt isPositive]
這句話就是從collection allAmounts返回所有positive的單元的集合。amt按我的理解就是對應的每個element。