Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

c++ - Why singleton classes cannot be sub-classed?

I was going through the negative effects of singleton. Here is one of the point that I cannot understand at all. Here is the link and the point.

Negative sides of Singleton

The following points are used against the Singleton pattern:

They deviate from the Single Responsibility Principle. A singleton class has the responsibility to create an instance of itself along with other business responsibilities. However, this issue can be solved by delegating the creation part to a factory object.

Singleton classes cannot be sub classed.

http://www.codeproject.com/Articles/307233/Singleton-Pattern-Positive-and-Negative-Aspects

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The article seems to be mostly written about the normal Java implementation of singleton, where the constructor is private; that means subclassing is impossible (the subclass is required to call the constructor, but can't). Allowing more access to the singleton means it can no longer be guaranteed to have only a single instance.

It's really an inherent contradiction; if you can subclass, then you can trivially create more instances (by just creating an otherwise empty subclass for each instance you want) so you don't really have a singleton.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...