为什么单例对象更面向对象? [英] Why are singleton objects more object-oriented?

查看:54
本文介绍了为什么单例对象更面向对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Scala 中编程:综合分步导,作者说:

Scala 更多的一种方式面向对象而不是 Java 的一点是Scala 中的类不能有静态成员.相反,Scala 有单例对象.

One way in which Scala is more object-oriented than Java is that classes in Scala cannot have static members. Instead, Scala has singleton objects.

为什么 singleton 对象更面向对象?不使用静态成员,而是使用单例对象有什么好处?

Why is a singleton object more object-oriented? What's the good of not using static members, but singleton objects?

推荐答案

尝试大局";其中大部分内容已包含在其他答案中,但似乎没有一个全面的回复将所有内容放在一起并连接点.所以这里是...

Trying for the "big picture"; most of this has been covered in other answers, but there doesn't seem to be a single comprehensive reply that puts it all together and joins the dots. So here goes...

类上的静态方法不是对象上的方法,这意味着:

Static methods on a class are not methods on an object, this means that:

  1. 静态成员不能从父类/特征继承
  2. 静态成员不能用于实现接口
  3. 类的静态成员不能作为参数传递给某些函数

  1. Static members can't be inherited from a parent class/trait
  2. Static members can't be used to implement an interface
  3. The static members of a class can't be passed as an argument to some function

(因为以上几点...)

对象的全部意义在于它们可以从父对象继承,实现接口,并作为参数传递——静态成员没有这些属性,所以它们不是真正的面向对象,它们只是一个命名空间.

The whole point of objects is that they can inherit from parent objects, implement interfaces, and be passed as arguments - static members have none of these properties, so they aren't truly object-oriented, they're little more than a namespace.

另一方面,单例对象是对象社区的成熟成员.

Singleton objects, on the other hand, are fully-fledged members of the object community.

单例的另一个非常有用的特性是它们可以很容易地在以后的某个时间点更改为不是单例,如果您从静态方法开始,这是一个特别痛苦的重构.

Another very useful property of singletons is that they can easily be changed at some later point in time to not be singletons, this is a particularly painful refactoring if you start from static methods.

假设您设计了一个程序来打印地址并通过某个类上的静态方法表示与打印机的交互,然后您希望能够添加第二台打印机并允许用户选择他们将使用的打印机.. 这不会是一次有趣的体验!

Imagine you designed a program for printing addresses and represented interactions with the printer via static methods on some class, then later you want to be able to add a second printer and allow the user to chose which one they'll use... It wouldn't be a fun experience!

这篇关于为什么单例对象更面向对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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