Differences between a static class and an instance class with a private constructor

Although a static class has only one instance and cannot be created, a class with a private constructor cannot be created (since the constructor cannot be seen), so every time you call this class, is it the same instance?

Factory classes always follow the last convention (instance class with private constructor). Why is this?

thanks

+4
source share
3 answers

Nothing stops a private constructor class from having an open static method that returns instances of the class:

public class NoPublicConstructor { private NoPublicConstructor() { } public static NoPublicConstructor NewInstance() { return new NoPublicConstructor(); } } 

As you can see, the static method does not return the same instance.

edit: One of the reasons factory classes are sharing responsibility in future versions: while your code always calls the factory creation method, the author can move all the guts from this class to another, and your code should not know the difference . A call to the constructor of this class (public) associates it to some extent with the original implementation of the class.

+4
source

You cannot * get an instance outside the class, but you can from the inside. A static method or inner class can create and return an instance of the class using a private constructor. A static class cannot be set by anything.

 class Foo { private Foo() { } public class Bar { public Bar() { } public Foo GetFoo() { return new Foo(); } } } 

..

 Foo.Bar fooBar = new Foo.Bar(); Foo foo = fooBar.GetFoo(); 

Edit: * I use the term "can not" freely. Brian Rasmussen pointed out in the comments on the OP that another method of obtaining an instance is a call through System.Runtime.Serialization.FormatterServices, and this is external to the class itself.

 Foo foo = (Foo)System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject(typeof(Foo)); 
+1
source

Creating a class with a private constructor is a common template for implementing a Singleton object.

Singleton will usually create an instance of itself and allow access to it through the static "Instance" property, which means that there is only one instance of the class.

The advantage of using Singleton over a purely static class is that you can use interfaces and different implementation classes in singleton. Your "Singleton" can provide an interface for a set of methods, and you can choose which implementation class should be created under the covers. If you were to use a purely static class, it would be difficult to replace a completely different implementation without affecting other code.

The main disadvantage of Singleton is that it is difficult to replace the implementation class with it, since it is controlled by Singleton's private methods, but there are ways around this.

0
source

Source: https://habr.com/ru/post/1305803/


All Articles