Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

c# - Why do I need the Singleton design pattern?

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();
                }
            }
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...