David Droddy
David Droddy

Reputation: 53

Singleton example

Gang of four uses a load balancer example to demonstrate the singleton pattern. I'm just wondering why a singleton needs to be used in that example? Are there any other real examples that specifically demonstrate using a singleton pattern?

I just want to know more specific reasons why I would want to prevent the creation of more than one instance of an object. And, I mean, if there were more than one load balancer instance, so what?

Upvotes: 0

Views: 1580

Answers (4)

Bill the Lizard
Bill the Lizard

Reputation: 405675

A load balancer can't be very effective if there is more than one of them working at a time. If one load balancer assigns work to a device, then another balancer comes along and assigns work to the same device, the system can easily become unbalanced. The multiple load balancers would need to communicate with each other in order to do their job. It's simpler and more efficient to have a single instance of the balancer.

Another example of an application that calls for a Singleton is a software module whose job it is to talk to a device on a serial port. I recently implemented a class for communicating with a motor controller and I wanted to be very sure there was only one class accessing the serial line. Implementing this class as a Singleton insured that two instances could never be created, avoiding contention on the serial line.

Upvotes: 2

bedwyr
bedwyr

Reputation: 5874

In one application, I had a manifest which was used to hold XML data retrieved from a server. This acted as a type of "cache" to prevent lookups from happening multiple times. Rather than passing a reference to the manifest from object to object, I created a Singleton which was accessed by whichever objects needed it at runtime.

Upvotes: 0

TheSean
TheSean

Reputation: 4566

If you have a client-server app, then your service may require only a client per connection. For example, I need to register a callback with my service:

public class myClient
{
    public myClient()
    {
        myService = // get service somehow
        myService.Init(myCallback);
    }
    public void myCallback() { /* do something*/}
}

if you create a second instance of myClient, you will overwrite the first callback with the second.

Upvotes: 0

John Rasch
John Rasch

Reputation: 63435

I just used one to instantiate a Flexwiki engine for an ASP.NET application because for that particular application I only needed the functionality to convert wiki syntax into HTML. The engine itself consumes a lot of memory, and I only need a small portion of it to fulfill my requirements. Additionally, it is not dependent on an individual user, so it can be stored in cache. Having another instance of the engine would be pointless as it serves no additional purpose other than to waste memory.

Upvotes: 0

Related Questions