Proper use of a singleton design template

I start a server that sometimes needs to look for client requests. I would like to write a client request to the disk for recordings, but I do not want to slow down the search more than I should. (Search is already a bottleneck ...)

So, when the client performs a search, I have a client thread that sends a message to a singleton thread that will handle writing to disk, while the client thread continues to process client requests. Thus, the file on disk does not encounter synchronization problems, and this does not slow down the operation of clients.

I have a conceptual question: is this singleton suitable in this case? I have used the singleton design pattern too much in my recent programming, and I want to make sure that I use it for its intended use.

Any feedback is welcome.

+8
java oop design-patterns singleton
source share
1 answer

The singleton pattern is definitely overestimated and comes with its share of difficulty (unit-testing is a canonical example), but, like everything in design, you need to weigh the pros and cons for your specific scenario. A singleton template has its own uses. There are options that can allow you to get singleton behavior while eliminating some of its inherent problems:

Interception (often called aspect-oriented programming, although I saw a debate that they are not quite the same ... might not find the article I read about it at this time) is definitely an option. You can use any combination of construction injection, decorator template, abstract factory, and inversion of the control container . I am not in my Java IoC containers, but there are some .Net containers that allow automatic interception (I believe Spring.Net does, so it is possible that Spring (Java) has this inline). This is very convenient for any type of cross-cutting tasks, when you need to perform certain actions at several levels (security, logging, etc.). In addition, most IoC containers allow you to manage lifelong management, so you can treat your logger as a singleton without actually implementing a singleton template manually.

Summarizing. If a singleton is suitable for your scenario (seems plausible from your description), go for it. Just make sure you weigh the pros and cons. You can try a different approach and compare two.

+7
source share

All Articles