不要静态成员自己创建类(全局)对象类吗? [英] Don't static members make classes kind of (global) objects themselves?

查看:156
本文介绍了不要静态成员自己创建类(全局)对象类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我遇到单例模式或任何静态类(即几乎只有静态成员的类)的实现,我不知道这是否不是一个黑客,因此严重滥用类和实例的原理只是设计单个对象,而不是设计类和创建单个实例。对我来说,看起来类的静态成员一般试图添加一些类型的特性,他们实际上是不应该有的,而是让它们自己的对象。

Every time I come across an implementation of the singleton pattern or any static classes (i.e. classes with (almost) only static members) I wonder whether this isn't actually a hack and therefore heavy abuse of the principle of classes and instances just to design single objects instead of designing classes and creating a single instance. To me, it looks like static members of classes in general try to add some sort of characteristics to classes which they actually aren't supposed to have and which rather make them object themselves.

但是是否真的需要像这样实现单个对象?
或者你看到的东西完全不同,不认为这样的静态类或单例与实际对象有什么共同之处?

But is it really desirable to have single objects implemented like that? Or do you see things completely differently and don't think that such static classes or singletons have anything in common with actual objects?

推荐答案

静态成员实际上只是全局变量的命名空间,是的。没有什么错误;命名空间是好的,全局是最干净的方式来完成一些任务。

Static members are effectively just namespacing for globals, yes. Nothing wrong with that; namespacing is good, and globals are the cleanest way to accomplish some tasks.

单例可以有点更有趣(按需加载...)构造(是的,你可以认为静态成员是由编译器管理的匿名单例)。

Singletons can be somewhat more interesting (load on demand...) but they're a similar construct (yeah, you could think of a static member as an anonymous singleton managed by the compiler).

像大多数东西一样,这些工具有它们的位置,只有意识形态担心他们是否适合某一特定的意识形态。

Like most things, these tools have their place, and only the ideologues worry about whether or not they "fit" with a particular ideology.

这篇关于不要静态成员自己创建类(全局)对象类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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