zoukankan      html  css  js  c++  java
  • ruby里面module和class的区别

    一句话概括,就是

    class可以实例化
    module不可以

    别的都一样

    关于继承的一点区别

    class是使用<作为继承的关键字,只支持单继承
    module是使用include来做实例继承(实例化的时候动态功能插入),extend做类继承(可以理解为static继承)

    module的应用场景

    作为namespace,里面放一般的const或者自己的class
    作为工具模块,放通用方法,别的类里面直接include或者extend以后使用,也可以看成动态扩展业务类
    可以作为抽象类,module里面提供默认实现,业务类include或者extend以后覆盖
    作为接口来用,一个可用的接口库,module-interface

    抽象类的例子

    module MyAbstract
      def walk
        puts 'abstract walk'
      end
    
      def run
        puts 'abstract run'
      end
    end
    
    class Person
      include MyAbstract
    
        def run
          puts 'person run'
        end
    
    end
    
    a = Person.new
    a.run
    a.walk

    接口的例子

    require 'module/interface'
    
    module Runnable
      def walk
      end
    
      def run
      end
    end
    
    class Person
      include Runnable
      extend Module::Interface
    
      interface Runnable do
        def run
          puts 'run'
        end
    
        def walk
          puts 'walk'
        end
      end
    
    end
    
    a = Person.new
    a.run
    a.walk
  • 相关阅读:
    SQL获取分组第一条记录
    Highcharts中Legend动态显示点值
    Json序列化
    Xml 序列化
    Json 用法整理
    Oracle如何复制表的sql语句
    spring.net 如何让xml智能提示
    C# 属性和字段的区别
    EasyUI中Grid标题居中方法(jquery实现方法)
    Asp.net Web.Config
  • 原文地址:https://www.cnblogs.com/ziyouchutuwenwu/p/4621257.html
Copyright © 2011-2022 走看看