如何每个类仅创建一个实例 [英] How to create only one instance per class

查看:121
本文介绍了如何每个类仅创建一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使在谷歌搜索后,我也没有找到完全合适的东西!

请帮助我.

修改:

有人可以用Singleton模式解释这一行吗?

Even after googling I didn''t find anything exactly fitting!

Please help me in this.

Modification:

Can somebody please explain this line in the Singleton pattern:

public class OnlyOne
{
    // Please explain this line too me
    private static OnlyOne instance = null;

    private OnlyOne()
    {
    }

    public static OnlyOne getInstance()
    {
        if(instance==null)
        {
            instance = new OnlyOne();
        }
        return instance;
    }
}

推荐答案

使用Singleton类是可能的.
检查此链接:

http://csharpindepth.com/Articles/General/Singleton.aspx [
That''s possible using a Singleton Class.
Check this link :

http://csharpindepth.com/Articles/General/Singleton.aspx[^]

The author provided a nice and elegant explanation to implement it, its thread safe too.

Hope it helped! :)


好的.您是否遇到过 class 这种称为 Singleton 类的设计模式?

此处:
http://msdn.microsoft.com/en-us/library/ff650316.aspx [ ^ ]
http://msdn.microsoft.com/en-us/library/ee817670.aspx [ ^ ]
Okay. Did you come across class the design pattern called Singleton class yet?

Here:
http://msdn.microsoft.com/en-us/library/ff650316.aspx[^]
http://msdn.microsoft.com/en-us/library/ee817670.aspx[^]


请在此处查看我对这个问题的解决方案:
Please see my solution to this question here: how to open only one instance of class not more than that ?[^]. Eventhough it''s for a windows form class the same principles apply for other classes too.
As Sandeep already pointed out there is a design pattern called Singleton, which will solve your problem.

To give you a hint:
The object creation from outside of the class is prohibited by making the constructor private. Anything marked private can only be accessed from within the class, but not from the outside.

Best Regards,


这篇关于如何每个类仅创建一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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