代码之家  ›  专栏  ›  技术社区  ›  Leonid Shevtsov

如何在Ruby中将类构造函数设置为私有?

  •  65
  • Leonid Shevtsov  · 技术社区  · 16 年前
    class A
    private
      def initialize
        puts "wtf?"
      end
    end
    
    A.new #still works and calls initialize
    

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

    new private,并通过工厂方法调用它。

    3 回复  |  直到 14 年前
        1
  •  91
  •   adurity    16 年前

    试试这个:

    class A
      private_class_method :new
    end
    

    More on APIDock

        2
  •  13
  •   Nathan    10 年前

    class A
      def initialize(argument)
        # some initialize logic
      end
    
      # mark A.new constructor as private
      private_class_method :new
    
      # add a class level method that can return another type
      # (not exactly, but close to `static` keyword in other languages)
      def self.create(my_argument)
         # some logic
         # e.g. return an error object for invalid arguments
         return Result.error('bad argument') if(bad?(my_argument))
    
         # create new instance by calling private :new method
         instance = new(my_argument)
         Result.new(instance)
      end
    end
    

    result = A.create('some argument')    
    

    正如预期的那样,在直接的情况下会发生运行时错误 new

    a = A.new('this leads to the error')
    
        3
  •  12
  •   Artur A    8 年前

    private

    得到 private :new 要工作,你只需要强制它在类方法的上下文中,如下所示:

    class A
      class << self
        private :new
      end
    end
    

    或者,如果你真的想重新定义 new 并呼叫 super

    class A
      class << self
        private
        def new(*args)
          super(*args)
          # additional code here
        end
      end
    end
    

    类级工厂方法可以访问私有 将失败,因为 是私人的。

    推荐文章