C#面向对象设计模式纵横谈(2):Singleton 单件(创建型模式) 笔记

(很喜欢李建忠老师的这个讲座,可惜暂时没更多的了,继续关注 MSDN WebCast 网络广播

C#面向对象设计模式纵横谈(2):Singleton 单件(创建型模式)



模式分类

 

 

目的

创建型

结构型

行为型

 

 

 

 

 

 

 

工厂方法(Factory Method

适配器(类,Adapter

解释器(Interpreter

模板方法(Template Method

 

 

 

 

抽象工厂(Abstract Factory

生成器(Builder

原型(Prototype

单件(Singleton

适配器(对象,Adapter

桥接(Bridge

组成(Composite

装饰(Decorator

外观(Facade

享元(Flyweight

代理(Proxy

职责链(Chain of Responsibility

  令(Command

迭代器(Iterator

中介者(Mediator

备忘录(Memento

观察者(Observer

  态(State

  略(Strategy

访问者(Visitor



动机(Motivation)


意图(Intent)


Singleton 模式实现

/// <summary>
/// 单线程 Singleton 模式实现
/// </summary>

public class Singleton
{
    
private static Singleton instance;

    
private Singleton() {}//私有的构造器使得外部无法创建该类的实例

    
public static Singleton Instance
    
{
        
get
        
{
            
if ( instance == null )
            
{
                instance 
= new Singletion();
            }

            
return instance;
        }

    }

}

/// <summary>
/// 多线程 Singleton 模式实现
/// </summary>

public class Singleton
{
    
private static volatile Singleton instance = null;

    
private static object lockHelper = new Object();

    
private Singleton() {}  //私有的构造器使得外部无法创建该类的实例



    
public static Singleton Instance
    
{
        
get
        
{
            
if ( instance == null )
            
{
                
lock ( lockHelper )
                
{
                    
if ( instance == null )
                    
{
                        instance 
= new Singletion();
                    }

                }

            }

            
return instance;
        }

    }

}


/// <summary>
/// 多线程 Singleton 模式实现
/// </summary>

class Singleton
{
    
public static readonly Singletion Instance = new Singleton();

    
private Singleton() {}
}


//// 等同于:

/// <summary>
/// 多线程 Singleton 模式实现
/// </summary>

class Singleton
{
    
public static readonly Singletion Instance;

    
static Singleton()
    
{
        Instance 
= new Singleton();
    }


    
private Singleton() { }
}

 
/// <summary>
/// 单线程 Singleton 模式实现
/// 支持参数化的构造器方式
/// </summary>

public class Singleton
{
    
public static readonly Singletion instance;

    
private Singleton(int x, int y)
    
{
        
this.x = x;
        
this.y = y;
    }


    
public static Singleton GetInstance(int x, int y0
    
{
        
if ( instance == null )
        
{
            instance 
= new Singleton(x, y);
        }

        
else
        
{
            instance.x 
= x;
            instance.y 
= y;
        }


        
return instance;

    }


    
int x;
    
int y;
}

原文地址:https://www.cnblogs.com/yyw84/p/272668.html