模式四(单子模式)
来源:互联网 发布:java面试简历下载 编辑:程序博客网 时间:2024/04/26 19:14
单例类只能有一个实例,单例类必须自己创建自己的唯一实例,单例类必须给所有其他对象提供这一事例。
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Generic;
using System.Text;
namespace Simple_Factory
{
class Singleton
{
/// <summary>
/// 私有的类对象
/// </summary>
private static Singleton instance;
{
class Singleton
{
/// <summary>
/// 私有的类对象
/// </summary>
private static Singleton instance;
protected Singleton() { }
public static Singleton Instance()
{
if (instance == null)
instance = new Singleton();
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
}
}
public class Client
{
public static void Main()
{
Singleton s1 = Singleton.Instance();
{
public static void Main()
{
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
if (s1 == s2)
Console.WriteLine("The same instance");
}
}
}
Console.WriteLine("The same instance");
}
}
}
写法二:
sealed class Singleton
{
private Singleton();
public static readonly Singleton Instance=new Singleton();
}
Singleton类被声明为sealed,以此保证它自己不会被继承,将原来的Instance()方法变成public readonly,并在声明时被初始化,于是在初始化Instance属性的同时Singleton类实例得以创建和装载,而私有的构造函数和readonly()保证了Singleton不会被再次实例化。
但是该方式的缺点,无法实现延迟初始化。
写法三:
public sealed class Singleton
{
Singleton(){}
public static Singleton GetInstance()
{
return Nested.instance;
}
class Nested
{
static Nested()
{}
internal static readonly Singleton instance=new Singleton();
}
}
- 模式四(单子模式)
- 单子模式
- 单子模式
- 设计模式---单子(Singleton)
- 单子(Singleton)设计模式
- 单子(Singleton)设计模式
- 单子设计模式解析(Singleton Pattern)
- 初识JAVA3(重载、单子模式)
- 单子设计模式
- 单子设计模式
- Singleton单子模式
- 单子模式 简介
- 单子设计模式
- Java单子模式
- 单例模式(单子模式)
- 单例模式(单子模式)
- 仿照单子模式的测试
- oracle数据库连接 单子模式详解
- 暑假10天
- WinXP控制远程桌面中的“雕虫小技”
- Oracle 客户端 NLS_LANG 的设置
- linux学习什么?
- My Google Docs Info
- 模式四(单子模式)
- PL/SQL产生XML的encoding的值
- 一个东大学生实现的一些算法
- 新闻二则:P≠NP有望得证 魔方问题告破
- 航天飞机的宽度是由马屁股决定的
- EXCEL 数据导入ORACLE的方法汇总(收集)
- ORACLE游标、递归查询、子查询与批量更新示例
- 判断单链表是否存在环,判断两个链表是否相交问题详解
- 0810工作日志