ruby學習筆記 2 訪問控制

2021-04-12 13:54:51 字數 1321 閱讀 1996

class singleton

#公開的

#預設不宣告許可權的物件都是公開的

#initialize除外,它總是私有的

public

def publicmethod

puts 'this is a public method'

end#私有的

private

def privatemethod

puts 'this is a private method'

end#愛保護的,僅由類和它的子類可以訪問

protected

def protectedmethod

puts 'this is a protect method'

end#或者也可以以這樣定義

def accessdefineinaotherpositionmethod

puts 'access define in aother position method'

end#物件必須在宣告訪問許可權之前已定義

protected :accessdefineinaotherpositionmethod

endclass singletonsubclass#私有構造

#這是乙個單件模式中常用的方法

#將構造宣告為私有的

#然後使用全域性惟一例項呼叫它

private_class_method:new

#全域性例項

@@instance=nil

#靜態方法,構造單件例項

def singleton.create

@@instance=new unless @@instance

end#公開父類的受保護方法

public

def accessdefineinaotherpositionmethod

super()

#子類可以呼叫父類受保護的物件

#但不能呼叫父類私有的物件

#比如在這兒呼叫privatemethod()是非法的

protectedmethod()

endend

singletonsubclass=singletonsubclass.create #singletonsubclass的惟一例項

singletonsubclass.publicmethod  #繼承來的公開方法

singletonsubclass.accessdefineinaotherpositionmethod #在singletonsubclass中,此方法是公開的

#singletonsubclass.privatemethod 這是非法的,只能在singleton內部被呼叫

ruby學習筆記 1 訪問物件屬性

在ruby中,運算子操作實際上也是方法呼叫,於是,我們就可以避免繁瑣的get,set方法了 class book def initialize name name name enddef name name enddef name new name name new name endend 但是如果...

ruby 學習筆記

usr bin ruby puts ruby 資料型別 puts ruby支援的資料型別包括基本的number string ranges symbols,以及true false和nil這幾個特殊值,同時還有兩種重要的資料結構 array和hash。puts n array n ary liqia...

Swift學習筆記系列 (24)訪問控制

tags swift 學習筆記 單個的類 結構體和列舉 屬於1的屬性 方法 構造方法和下標 協議的適用範圍 訪問控制的基礎 一系列 xcode中的乙個構造目標 單獨的源 檔案 本模組的任意原始檔內可以訪問 匯入所在模組的其他模組的原始檔可以訪問 預設的訪問級別 同一模組的任意源 中都可以訪問 同一原...