怀疑 类 其中只有一个实例

Be suspicious of classes of which there is only one instance

tl;dr -- 下面引用的段落是什么意思?

Be suspicious of classes of which there is only one instance. A single instance might indicate that the design confuses objects with classes. Consider whether you could just create an object instead of a new class. Can the variation of the derived class be represented in data rather than as a distinct class? The Singleton pattern is one notable exception to this guideline.

McConnell, Steve (2004-06-09). Code Complete (2nd Edition)

加长版:

我正在阅读 Code Complete,但我无法理解上述段落。对于上下文,它来自第 6 章的继承指南。起初我认为这是反对使用单例的建议,但当我读到本段结尾时显然我错了。

我简直无法理解作者试图通过我厚厚的头骨得到什么。例如,我不知道他所说的用 classes 设计混淆对象是什么意思,也不知道在只有一个实例的 class 的上下文中这意味着什么。求助!

那里的措辞相当混乱,但我相信这意味着有时新手程序员可能会创建一个全新的类型来实例化它的一个对象。作为一个特别明显的例子:

struct Player1Name
{
    string data;
};

在那里我们可以只使用 string player1_name;(或者甚至是多个玩家的聚合)而不创建一个全新的类型,因此尝试使用 classes 来模拟新对象的混淆(现有类型的新实例)已经可以做到。

在这种情况下,开发人员可能会使用数百种新的用户定义的数据类型和可能的大量继承层次结构向代码库发送垃圾邮件,而单个 class 不可能在每个实例之外重复使用当现有 classes 通常足够时,他想创建一个新事物。

The real problem is not that the classes are being instantiated once, but that their design is so narrowly applicable as to only be worth instantiating once.

类 通常是为了模拟与其实例(对象)的一对多关系。它们应该至少比 class 的单个实例更普遍适用。粗略地说,class 应该模仿 Dog,而不是邻居的特定宠物狗 Spark。它应该模拟 Rectangle,而不是 4.2 米 x 8.7 米的精确 Rectangle42x87。如果您正在设计一次性实例化的事物,那么您可能将它们设计得太狭隘,并且可能有现有的事物可以代替使用。

一种新的数据类型通常旨在解决 class(类别)问题,可以这么说,而不是一个非常精确的问题,它只需要 class 的一个实例。否则,您的 class 设计将是一次性交易,只是表面上到处创建 classes 来解决非常个别的问题,没有任何广泛应用的潜力。

单例是规则的一个例外,因为它没有以这种正常的面向对象的方式利用 classes。它故意着手创建一个单一的实例,惰性构造,并具有全局访问点。因此,开发人员创建一个旨在实例化一次的 class 并非出于某种意外和对面向对象设计的误解。可以说,这是一个非常深思熟虑和有意识的设计决定,而不是对如何使用这些工具的误解。