Home » Design Pattern » Singleton

Singleton

作者:

分類:

Singleton

Singleton Concept

The Singleton pattern is a creational design pattern that ensures a class has only one instance in the program.

In industrial control programming, there is often a need to control external hardware information.

To prevent confusion caused by the repeated creation of objects that control hardware, the Singleton pattern proves to be a practical solution.

Why not use a static class? While a static class also represents a unique instance in the program, the key difference lies in the foundation of the pattern being a class.

This allows it to be inherited and passed as a parameter, providing more flexibility compared to a static class.

Singleton Example

//**************
//* author: cian
//* 20231002
//**************

/* Singleton */
public class Singleton 
{
  private static Singleton INSTANCE = new Singleton();
  
  private Singleton() {}; /*hide constructor*/
 
  public static Singleton GetInstance()
  {
    return INSTANCE;
  }
}

/* usage */
Singleton mySingleton = Singleton.GetInstance();

Conclusion

The pattern proves to be a valuable choice when there is a need for a single instance of a global variable in a system.

However, it is essential to exercise caution and not indiscriminately incorporate everything into it, as this can lead to unclear responsibilities and make debugging more challenging.

Striking the right balance in utilizing the pattern ensures its effectiveness without sacrificing the clarity and maintainability of the codebase.

References

cian Avatar

留言

Leave a Reply

Your email address will not be published. Required fields are marked *