如何使类的构造函数私有在Ruby? [英] How to make the class constructor private in Ruby?

查看:147
本文介绍了如何使类的构造函数私有在Ruby?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class A 
private
def initialize
putwtf?
end
end

A.new #still工作和调用initialize

  class A 
private
def self.new
super.new
end
end

>

那么什么是正确的方法呢?我想让 new private并通过工厂方法调用。

解决方案

p>尝试:

  A类
private_class_method:new
end

更多APIDock


class A
private
  def initialize
    puts "wtf?"
  end
end

A.new #still works and calls initialize

and

class A
private
  def self.new
    super.new
  end
end

doesn't work altogether

So what's the correct way? I want to make new private and call it via a factory method.

解决方案

Try this:

class A
  private_class_method :new
end

More on APIDock

这篇关于如何使类的构造函数私有在Ruby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆