惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队
The Cloudflare Blog
量子位
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园_首页
F
Fortinet All Blogs
J
Java Code Geeks
人人都是产品经理
人人都是产品经理
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
爱范儿
爱范儿
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog RSS Feed
博客园 - 聂微东
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
小众软件
小众软件
Y
Y Combinator Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Vercel News
Vercel News
S
SegmentFault 最新的问题
有赞技术团队
有赞技术团队

博客园 - Tristan(GuoZhijian)

Core Design Patterns(16) Chain of Responsibility 职责链模式 Core Design Patterns(15) Template Method 模版方法模式 Core Design Patterns(14) State 状态模式 Core Design Patterns(13) Strategy 策略模式 Core Design Patterns(12) Builder 建造者模式 Core Design Patterns(11) Abstract Factory 抽象工厂模式 Core Design Patterns(9) Factory Method 工厂方法模式 Core Design Patterns(8) Prototype 原型模式 Core Design Patterns(7) Facade 外观模式 Core Design Patterns(6) Adapter 适配器模式 Core Design Patterns(5) Flyweight 享元模式 Core Design Patterns(4) Composite 组合模式 Core Design Patterns(3) Bridge 桥接模式 Core Design Patterns(2) Proxy 代理模式 Core Design Patterns(1) Decorator 装饰模式 老调重弹:插件式框架开发的一个简单应用 Behavior模型应用:可拖动的div容器 Microsoft Asp.Net Ajax框架入门(13) PageRequestManager Microsoft Asp.Net Ajax框架入门(12) 了解异步通信层
Core Design Patterns(10) Singleton 单例模式
Tristan(GuoZhijian) · 2008-03-15 · via 博客园 - Tristan(GuoZhijian)

VS 2008

使用单例模式,可以控制一个类在一个应用程序中只有一个实例。

1. 模式UML图

2. 代码示意
2.1 最简单的单例模式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Singleton.BLL {
    
public class Singleton {

        
private static Singleton singleton = new Singleton();

        
private Singleton() { }

        
public static Singleton GetInstance() {
            
return singleton;
        }

    }

}

2.2 Lazy instantiation and double checked locking

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPattern.Singleton.BLL {
    
public class LazySingleton {

        
private static LazySingleton singleton = null;
        
private static object objLock = new object();

        
private LazySingleton() { }

        
public static LazySingleton GetInstance() {
            
if (singleton == null{
                
lock (objLock) {
                    
if (singleton == null{
                        singleton 
= new LazySingleton();
                    }

                }

            }

            
return singleton;
        }

    }

}