Why do I need the Singleton design pattern?


Question

i try to learn design pattern, but it's really really hard to understand main idea of OOD. i have created my software with classic method. On the other hand i want to learn OOD. why i need singleton and others? i coded some simple program: one of them clasical(my style), the other is singleton pattern.Please teach me why do i need singleton. my method better and clear than it :)

my style: (C#)


  public partial class Singletonsuz : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Loadbalancer balancer = new Loadbalancer();

        for (int i = 0 ; i < 15 ; i++)
        {
            string server = balancer.Server;
            Response.Write("Dispatch Request to: " + server);
        }
    }
}
class Loadbalancer
{
    private List<string> _servers = new List<string>();
    private Random _random = new Random();
    public Loadbalancer()
        {
            _servers.Add("ServerI");
            _servers.Add("ServerII");
            _servers.Add("ServerIII");
            _servers.Add("ServerIV");
            _servers.Add("ServerV");
        }
    public string Server
    {
        get
        {
            int r = _random.Next(_servers.Count);
            return _servers[r].ToString();
        }
    }
}

SINGLETON:


    public partial class SingletonDP2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoadBalancer balancer = LoadBalancer.GetLoadBalancer();
            for (int i = 0; i < 15; i++)
            {
                string server = balancer.Server;
                Response.Write("Dispatch Request to: " + server );
            }
        }

        class LoadBalancer
        {
            private static LoadBalancer _instance;
            private List<string> _servers = new List<string>();
            private Random _random = new Random();

            private static object syncLock = new object();
            protected LoadBalancer()
            {
                _servers.Add("ServerI");
                _servers.Add("ServerII");
                _servers.Add("ServerIII");
                _servers.Add("ServerIV");
                _servers.Add("ServerV");
            }

            public static LoadBalancer GetLoadBalancer()
            {
                if (_instance == null)
                {
                    lock (syncLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new LoadBalancer();
                        }
                    }
                }
                return _instance;
            }

            public string Server
            {
                get
                {
                    int r = _random.Next(_servers.Count);
                    return _servers[r].ToString();
                }
            }
        }
    }
1
2
1/27/2009 8:49:55 AM

Design patterns are not a design or development methodology. They are a vocabulary: they help putting names on recurring patterns that occur in software architectures. From my experience, designing a software FROM patterns ends up in hairy software with a lot of single-purpose classes, which increases the number of things that the programmer must have in mind (and software development is complicated enough to avoid filling your brain with noise).

However design patterns come very handy at a later stage. Always start with your specific problem and domain, try to find solutions, and identify patterns in the process. Don't start with the patterns, trying to force-fit your problem into them. Knowledge of the most common patterns is a must, as it eases communication between programmers (be they developer or library users) and promotes good practices.

For example, let's suppose that your problem deals with sets of data. At some point you've built your data structures and algorithms. Now you (or someone else) need to access your data in a higher level way. This is the typical case where the Iterator or Visitor patterns can apply. That's the way it has been done in the C++ STL, where all collection classes understand iterators. However you don't need to think upfront about the patterns you may or may not apply here or there, there is always a time to refactor things once patterns or needs have been identified.

Design patterns originally come from building and architecture, which are very similar to software development in many ways. From my experience the best way to understand DPs is through analogy with architecture: software is the building, patterns are the way architectural elements are organized: windows, doors, corridors, stairs, lights... Architects don't think about the elements they want to use, but think about the effect they want to get. For example, an architect might think: this staircase needs light. To achieve this, he may use windows, skylights, glass blocks, artificial lights, etc., according to the architectural constraints, building code, his client's taste, etc. He doesn't arbitrarily choose elements before thinking about the problem he's trying to solve, unless he's trying to achieve an effect or style. Moreover, if another solution becomes available on the market (e.g. reflective sunlight tunnels) then he may integrate it in the available design patterns for his future projects. OTOH if he takes the habit of thinking about solutions before thinking about problems, he takes the risk of missing alternative solutions, complicating the problem, or not solving it at all.

Here you've used the Singleton pattern for what appears to be a global object needing dynamic initialization. In this case the Singleton is an acceptable solution. However sometimes you would need more complex solutions because of external constraints (e.g. you need to initialize the objects in a certain order), and Singleton would no longer be appropriate. Or the object would only need static initialization and a plain global variable would fit your needs.

Overusing design patterns is as bad as not using them where they are needed. Choosing whether to use some pattern or not comes with knowledge and experience on software design and development in general, and your field in particular.

28
1/27/2009 1:16:02 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon