##########################   Singletons and other Constructors   ##################
class MyLogger
 private_class_method:new
 @@logger = nil
 def MyLogger.create
  @@logger = new unless @@logger
  @@logger
 end
end

###########################   Access Control   ###########################
#Ruby gives you three levels of protection.
#Public methods can be called by anyone—no access control is enforced.Methods
#are public by default (except for initialize, which is always private).
#Protected methods can be invoked only by objects of the defining class and its
#subclasses. Access is kept within the family.
#Privatemethods cannot be called with an explicit receiver—the receiver is always
#self. This means that private methods can be called only in the context of the
#current object; you can’t invoke another object’s private methods.
#Ruby differs from other OO languages in another important way. Access control is
#determined dynamically, as the program runs, not statically. You will get an access
#violation only when the code attempts to execute the restricted method.


#############################   Specifying Access Control   #################
class MyClass
 def method1  #default is 'public'
  #...
 end
 
 protected
  def method2
   #...
  end
 private
  def method3
   #...
  end
 public
  def method4
   #...
  end
end

#Alternatively, you can set access levels of named methods by listing them as arguments
#to the access control functions.
class MyClass
 def method1
 end
 #...and so on
 public :method1, :method4
 protected :method2
 private :method3
end

class Accounts
 def initialize(checking, savings)
  @checking = checking
  @savings = savings
 end
 private
  def debit(account, amount)
   account.blance -= amount
  end
  def credit(account, amount)
   account.blance += amount
  end
 public
  def transfer_to_saving(amount)
   debit(@checking, amount)
   credit(@savings, amount)
  end
end

class Account
 attr_reader :blance
 protected
  :blance
  
  def greater_balance_than(other)
   return @blance > other.balance
  end
end

######################   Variables   #######################
person = "Tim"
puts person.id  #936870
puts person.class  #String
puts person  #"Tim"

#is a variable an object? In Ruby, the answer is “no.”
#A variable is simply a reference to an object.

person1 = "Tim"
person2 = person1

person1[0] = "J"

person1  #"Jim"
person2  #"Jim"

#you could avoid aliasing by using the dup method of
#String, which creates a new String object with identical contents.

person1 = "Tim"
person2 = person1.dup
person1[0] = "J"
person1  #"Jim"
person2  #"Tim"

person1 = "Tim"
person2 = person1
person1.freeze    #prevent modifications to the object
person2[0] = "j"  #*****error

posted on 2008-02-19 21:20  IT Person  阅读(289)  评论(0编辑  收藏  举报