如何在 ruby​​ 中实现抽象类? [英] How to implement an abstract class in ruby?

查看:30
本文介绍了如何在 ruby​​ 中实现抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 ruby​​ 中没有抽象类的概念.但是,如果真的需要实施,该怎么做呢?我试过类似...

I know there is no concept of abstract class in ruby. But if at all it needs to be implemented, how to go about it? I tried something like...

class A
  def self.new
    raise 'Doh! You are trying to write Java in Ruby!'
  end
end

class B < A
  ...
  ...
end

但是当我尝试实例化 B 时,它会在内部调用 A.new 这将引发异常.

But when I try to instantiate B, it is internally going to call A.new which is going to raise the exception.

此外,模块不能被实例化,但也不能被继承.将新方法设为私有也不起作用.有什么指点吗?

Also, modules cannot be instantiated but they cannot be inherited too. making the new method private will also not work. Any pointers?

推荐答案

我不喜欢在 Ruby 中使用抽象类(几乎总有更好的方法).如果你真的认为这是最适合这种情况的技术,你可以使用以下代码片段来更明确地说明哪些方法是抽象的:

I don't like using abstract classes in Ruby (there's almost always a better way). If you really think it's the best technique for the situation though, you can use the following snippet to be more declarative about which methods are abstract:

module Abstract
  def abstract_methods(*args)
    args.each do |name|
      class_eval(<<-END, __FILE__, __LINE__)
        def #{name}(*args)
          raise NotImplementedError.new("You must implement #{name}.")
        end
      END
      # important that this END is capitalized, since it marks the end of <<-END
    end
  end
end

require 'rubygems'
require 'rspec'

describe "abstract methods" do
  before(:each) do
    @klass = Class.new do
      extend Abstract

      abstract_methods :foo, :bar
    end
  end

  it "raises NoMethodError" do
    proc {
      @klass.new.foo
    }.should raise_error(NoMethodError)
  end

  it "can be overridden" do
    subclass = Class.new(@klass) do
      def foo
        :overridden
      end
    end

    subclass.new.foo.should == :overridden
  end
end

基本上,您只需使用抽象方法列表调用abstract_methods,当它们被抽象类的实例调用时,将出现NotImplementedError 异常提升.

Basically, you just call abstract_methods with the list of methods that are abstract, and when they get called by an instance of the abstract class, a NotImplementedError exception will be raised.

这篇关于如何在 ruby​​ 中实现抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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