ruby学习笔记(2)--访问控制

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
 end
 
class SingletonSubClass<Singleton
   #私有构造
   #这是一个单件模式中常用的方法
   #将构造声明为私有的
   #然后使用全局惟一实例调用它
  private_class_method:new
  #全局实例
  @@Instance=nil
  #静态方法,构造单件实例
  def Singleton.Create
     @@Instance=new unless @@Instance
   end
  #公开父类的受保护方法
  public
  def AccessDefineInAotherPositionMethod
    super()
    #子类可以调用父类受保护的对象
    #但不能调用父类私有的对象
    #比如在这儿调用PrivateMethod()是非法的
    ProtectedMethod()
  end
 
end

singletonSubClass=SingletonSubClass.Create #SingletonSubClass的惟一实例
singletonSubClass.PublicMethod  #继承来的公开方法
singletonSubClass.AccessDefineInAotherPositionMethod #在SingletonSubClass中,此方法是公开的
#singletonSubClass.PrivateMethod 这是非法的,只能在singleton内部被调用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值