Chủ Nhật, 17 tháng 5, 2020

Singleton Pattern

1 singleton là 1 class mà chỉ cho phép 1 instance (thể hiện) đc tạo.

It is often used to create a single point of entry to a third party, such as a database or web service, so that the number of connections can be easily managed and configured in one place.
ex: problem of singleton

The approach here is called lazy initialization: The Singleton instance is only created when it is first needed. At first glance, it looks like any other calls to getInstance() will return that same instance. If, however, INSTANCE is null, and a thread is switched after the if statement but before INSTANCE is initialized, then a second (or more) thread calling getInstance() will also have the if statement return true and create a new object. This can result in strange, erratic behavior or worse, memory leaks resulting in the JVM eventually crashing.
Java 5 introduced the Enum type. If you create the Singleton as a single-element Enum, the JVM guarantees that only one instance will ever be created

Be aware that using the Singleton Pattern can lead to other issues: It can be very difficult to test in isolation, especially if the Singleton performs heavyweight operations, such as writing to a database. It is often better to simply manage any “singleton-like” object as a dependency on a class, and use a dependency injection framework to construct only one object.
Singletons work best in specialized applications, such as a GUI on a desktop or mobile application

Happy coding

thelam92

0 nhận xét:

Đăng nhận xét