Java Q & A: Use the Singleton mode? Give me a reason!

zhaozj2021-02-11  206

Java Q & A: Use the Singleton mode? Give me a reason!

Q: I have seen the Singleton class in many places. My question is: What is the advantage of using Singleton more than one class containing the Static Method (METHDS)?

A: Use Singleton without using classes containing the Static method, the difference is that the latter can bring effective object-oriented design. Singleton usually demonstrates a clearer way. And a class containing the Static method is just a simple column of a function or utility subroutine (utilities).

You will ask, what is the problem with a group of functions?

Very simple. The Row List, you are not working-oriented; your job is actually retreating to the traditional process-oriented programming. Sadness between, the object is no longer the focus of the program, and you also fall into the data-centered programming mode. In other words, you no longer send messages to the objects and behaviors, but a function call for data. The public subroutine will inevitably cause the behavior and data to be completely separated, and this is never allowed in object-oriented design.

It is not to say that the public subroutine cannot be used. Object-oriented public subroutines do exist. Sometimes it also needs to be processed as data. For example, I have written a common subsystem to convert Java objects into a corresponding CORBA form. It is difficult to write those methods into a class because they do not have status information; I don't want to embed the conversion code into the Java class. However, this is really easy to bring confusion.

For a class in the system, if you want it to exist any instance, you can use Singleton. For example, there is such a class that provides access to CORBA Server, but also load balancing. Don't use multiple such objects at this time because each object will deal with the same server. It is of course wasteful to occupy redundant resources. So, the access to Server is best concentrated in an instance.

转载请注明原文地址:https://www.9cbs.com/read-4430.html

New Post(0)