为什么我需要Singleton设计模式? [英] Why do I need the Singleton design pattern?

查看:141
本文介绍了为什么我需要Singleton设计模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试去学习设计模式,但它的的确确是很难理解OOD的主要思想。我创建了我的软件与传统方法。另外我想学习OOD。为什么我需要单身人士和其他人呢? I codeD一些简单的程序:他们clasical(我的风格)的一种,另一种是单pattern.Please教我?为什么我需要单。我的方法更好的和明确的比:)

我的风格:(C#)

 
  公共部分类Singletonsuz:System.Web.UI.Page
{
    保护无效的Page_Load(对象发件人,EventArgs的)
    {
        负载平衡器平衡器=新的负载均衡器();

        的for(int i = 0;我<15;我++)
        {
            字符串服务器= balancer.Server;
            回复于(调度请求:+服务器);
        }
    }
}
类负载平衡器
{
    私人名单的_servers =新的List 的();
    私人随机_random =新的随机();
    公共负载均衡器()
        {
            _servers.Add(服务器I);
            _servers.Add(ServerII);
            _servers.Add(ServerIII);
            _servers.Add(ServerIV);
            _servers.Add(ServerV);
        }
    公共字符串服务器
    {
        得到
        {
            INT R = _random.Next(_servers.Count);
            返回_servers [R]的ToString();
        }
    }
}
 

辛格尔顿:

 
    公共部分类SingletonDP2:System.Web.UI.Page
    {
        保护无效的Page_Load(对象发件人,EventArgs的)
        {
            负载平衡器平衡器= LoadBalancer.GetLoadBalancer();
            的for(int i = 0;我<15;我++)
            {
                字符串服务器= balancer.Server;
                回复于(调度请求:+服务器);
            }
        }

        类负载平衡器
        {
            私有静态负载平衡器_instance;
            私人名单的_servers =新的List 的();
            私人随机_random =新的随机();

            私有静态对象SYNCLOCK =新的对象();
            保护负载平衡器()
            {
                _servers.Add(服务器I);
                _servers.Add(ServerII);
                _servers.Add(ServerIII);
                _servers.Add(ServerIV);
                _servers.Add(ServerV);
            }

            公共静态负载平衡器GetLoadBalancer()
            {
                如果(_instance == NULL)
                {
                    锁定(SYNCLOCK)
                    {
                        如果(_instance == NULL)
                        {
                            _instance =新的负载平衡器();
                        }
                    }
                }
                返回_instance;
            }

            公共字符串服务器
            {
                得到
                {
                    INT R = _random.Next(_servers.Count);
                    返回_servers [R]的ToString();
                }
            }
        }
    }
 

解决方案

设计模式是不是设计或开发的方法的。他们是一个的词汇的:他们帮助把名字就经常性发生的软件架构模式。从我的经验,在设计软件从模式结束了在毛状软件与很多单一用途的类,这增加的东西,程序员必须具有记(和软件开发复杂足够,以避免与噪声填充大脑数)。

不过设计模式来非常方便在以后的阶段。总是与你的特定问题和领域入手,试图找到解决方案,并确定在此过程中的模式。不要与模式入手,试图迫使-适合您的问题纳入其中。知识的最常见模式是必须的,因为它简化了程序员之间的通信(无论是开发商或库的用户),促进良好做法。

例如,假设您的问题处理的数据集。在某些时候,你建立你的数据结构和算法。现在,您(或其他人)需要访问你的数据在一个较高的水平的方式。这是典型的情况下迭代器或访客模式可以适用。这是它在C ++ STL中,所有集合类理解迭代器已经做的方式。然而,你不需要考虑前期你可能会或可能不会在这里或那里应用模式,总有一个时间来重构东西一旦模式或需求已经确定。

设计模式最初来自建筑物和结构,该结构是非常相似的软件开发在许多方面。从我的经验,了解移民的最好办法就是通过类比与建筑:软件建设,模式是建筑元素的组织方式:窗,门,走廊,楼梯,灯......建筑师没有想到的元素,他们想用,但想想他们希望得到的效果。例如,建筑师可能会想:这个楼梯需要的光。为了实现这一目标,他可以利用窗户,天窗,玻璃砖,人造灯等,根据建筑的限制,建立code,他的客户的口味,等他思考的问题之前没有任意选择的元素他试图解决的,除非他想要达到的效果和风格。此外,如果另一种解决方案成为目前市场(如反射太阳光隧道)上,然后他可能会在现有的设计模式,为他日后的项目整合它。 OTOH如果他需要思考的问题之前,考虑解决方案的习惯,他把丢失的替代解决方案,复杂的问题,还是没有解决它在所有的风险。

在这里,你已经使用Singleton模式的似乎是需要动态初始化一个全局对象。在这种情况下,单件是可接受的解决方案。但是有时候你需要更复杂的解决方案,因为外部的约束(例如,你需要初始化以特定顺序的对象),和辛格尔顿将不再是合适的。或对象将只需要静态初始化和一个普通的全局变量会满足您的需求。

过度使用设计模式是一样糟糕,没有使用他们需要的地方。选择是否使用某种模式或不带有知识和软件的设计和开发的一般经验,特别是你的领域。

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();
                }
            }
        }
    }

解决方案

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.

这篇关于为什么我需要Singleton设计模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆