类和模块之间的区别 [英] Difference between a class and a module

查看:83
本文介绍了类和模块之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自Java,现在我使用ruby工作。我不熟悉的一个语言功能是模块。我想知道什么是一个模块,什么时候使用一个?

I came from Java and now I am working more with ruby. One language feature I am not familiar with is the module. I am wondering what exactly is a module and when do you use one? Also why use a module over a class?

推荐答案

第一个答案是好的,并给出了一些结构性的答案,但另一种方法是想想你在做什么。模块是关于提供可以跨多个类使用的方法 - 将它们看作库(就像你在Rails应用程序中看到的)。类是关于对象;模块是关于函数。

The first answer is good and gives some structural answers, but another approach is to think about what you're doing. Modules are about providing methods that you can use across multiple classes - think about them as "libraries" (as you would see in a Rails app). Classes are about objects; modules are about functions.

例如,身份验证和授权系统是模块的好例子。认证系统跨多个应用程序级类(用户进行身份验证,会话管理身份验证,许多其他类将根据身份验证状态采取不同的行为)工作,因此身份验证系统充当共享API。

For example, authentication and authorization systems are good examples of modules. Authentication systems work across multiple app-level classes (users are authenticated, sessions manage authentication, lots of other classes will act differently based on the auth state), so authentication systems act as shared APIs.

当您在多个应用程式间使用共用方法时,您也可以使用模组(同样,库模型在这里很好用)。

You might also use a module when you have shared methods across multiple apps (again, the library model is good here).

这篇关于类和模块之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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