Вопрос: Разница между статическим классом и одноэлементным шаблоном?


Какая реальная (т. Е. Практическая) разница между статическим классом и одноэлементным шаблоном?

Оба могут быть вызваны без экземпляра, оба обеспечивают только один «экземпляр», и ни один из них не является потокобезопасным. Есть ли другая разница?


1472


источник


Ответы:


Что заставляет вас сказать, что либо одноэлементный, либо статический метод не является потокобезопасным? Обычно оба должен быть реализованы для обеспечения поточности.

Большая разница между одиночным тоном и множеством статических методов заключается в том, что синглтоны могут реализовывать интерфейсы (или получать из полезных базовых классов, хотя это и не так часто встречается в моем опыте), поэтому вы можете обойти синглтон, как если бы это было «просто другое " реализация.


1026



Истинный ответ: Джон Скит, на другом форуме здесь ,

Один синглтон позволяет получить доступ к одному   созданный экземпляр - этот экземпляр (или   скорее, ссылка на этот экземпляр)   может передаваться как параметр в другой   методы и рассматриваются как нормальные   объект.

Статический класс допускает только статический   методы.


401



  1. Объекты Singleton хранятся в отвал , но статические объекты хранятся в стек ,
  2. Мы можем клон (если разработчик не запретил) объект singleton, но мы не можем клонировать объект статического класса ,
  3. Одиночные классы следуют OOP (объектно-ориентированные принципы), статические классы этого не делают.
  4. Мы можем реализовать interfaceс классом Singleton, но статические методы класса (или, например, C # static class) не могу.

323



The Singleton pattern has several advantages over static classes. First, a singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members). A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues. However the most important advantage, though, is that singletons can be handled polymorphically without forcing their users to assume that there is only one instance.


121



static classes should not do anything need state, it is useful for putting bunch of functions together i.e Math (or Utils in projects). So the class name just give us a clue where we can find the functions and there's nothing more.

Singleton is my favorite pattern and use it to manage something at a single point. It's more flexible than static classes and can maintain state. It can implement interfaces, inherit from other classes and allow inheritance.

My rule for choosing between static and singleton:

If there are bunch of functions should be kept together, then static is the choice. Anything else which needs single access to some resources, could be implemented singleton.


55



Static Class:-

  1. You cannot create the instance of static class.

  2. Loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.

  3. Static Class cannot have constructor.

  4. We cannot pass the static class to method.

  5. We cannot inherit Static class to another Static class in C#.

  6. A class having all static methods.

  7. Better performance (static methods are bonded on compile time)

Singleton:-

  1. You can create one instance of the object and reuse it.

  2. Singleton instance is created for the first time when the user requested.

  3. Singleton class can have constructor.

  4. You can create the object of singleton class and pass it to method.

  5. Singleton class does not say any restriction of Inheritance.

  6. We can dispose the objects of a singleton class but not of static class.

  7. Methods can be overridden.

  8. Can be lazy loaded when need (static classes are always loaded).

  9. We can implement interface(static class can not implement interface).


49



A static class is one that has only static methods, for which a better word would be "functions". The design style embodied in a static class is purely procedural.

Singleton, on the other hand, is a pattern specific to OO design. It is an instance of an object (with all the possibilities inherent in that, such as polymorphism), with a creation procedure that ensures that there is only ever one instance of that particular role over its entire lifetime.


47



In singleton pattern you can create the singleton as an instance of a derived type, you can't do that with a static class.

Quick Example:

if( useD3D )
    IRenderer::instance = new D3DRenderer
else
    IRenderer::instance = new OpenGLRenderer

32



To expand on Jon Skeet's Answer

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that's less common IME), so you can pass around the singleton as if it were "just another" implementation.

Singletons are easier to work with when unit testing a class. Wherever you pass singletons as a parameter (constructors, setters or methods) you can instead substitute a mocked or stubbed version of the singleton.


21



Another advantage of a singleton is that it can easily be serialized, which may be necessary if you need to save its state to disc, or send it somewhere remotely.


18



I'm not a great OO theorist, but from what I know, I think the only OO feature that static classes lack compared to Singletons is polymorphism. But if you don't need it, with a static class you can of course have inheritance ( not sure about interface implementation ) and data and function encapsulation.

The comment of Morendil, "The design style embodied in a static class is purely procedural" I may be wrong, but I disagree. In static methods you can access static members, which would be exactly the same as singleton methods accessing their single instance members.

edit:
I'm actually thinking now that another difference is that a Static class is instantiated at program start* and lives throughout the whole life span of the program, while a singleton is explicitly instantiated at some point and can be destroyed also.

* or it may be instantiated at first use, depending on the language, I think.


17



Here's a good article: http://javarevisited.blogspot.com.au/2013/03/difference-between-singleton-pattern-vs-static-class-java.html

Static classes

  • a class having all static methods.
  • better performance (static methods are bonded on compile time)
  • can't override methods, but can use method hiding. (What is method hiding in Java? Even the JavaDoc explanation is confusing)

    public class Animal {
        public static void foo() {
            System.out.println("Animal");
        }
    }
    
    public class Cat extends Animal {
        public static void foo() {  // hides Animal.foo()
            System.out.println("Cat");
        }
    }
    

Singleton

In summary, I would only use static classes for holding util methods, and using Singleton for everything else.


Edits


16