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

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

问题描述

我来自 Java,现在我更多地使用 Ruby.

I came from Java, and now I am working more with Ruby.

我不熟悉的一种语言特性是 module.我想知道 module 到底是什么,什么时候使用,为什么在 class 上使用 module?

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, and 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天全站免登陆