首页 > 代码库 > .NET设计模式之(单例模式)
.NET设计模式之(单例模式)
1.单例模式,一个类只能new一个对象
2.举例,资源管理器,文件管理器,地球等;
3.创建单例:
(1)创建一个Earth类
class Earth
{
public Earth()
{
}
}
(2)将构造函数 私有化
class Earth
{
private Earth()
{
}
}
(3)声明一个静态私有的字段,初始化一个实例class Earth
{
private static Earth instance=new Earth();
private Earth()
{
}
}
(4)编写一个静态方法或属性,返回唯一的实例class Earth
{
private static Earth instance=new Earth();
public static Earth GetEarth()
{
return instance;
}
private Earth()
{
}
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。