Design Pattern:Singleton

一定义: 单例模试的意思就是只有一个实例,单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。

二UML类图:


三模试角色与结构:

Singleton:负责创建单例并向整个系统提供这个单例。

四程序举例:

1、双重锁定实现

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 
 namespace Singleton
 {
     class Singleton
     {
         static Singleton s;
         private Singleton() { }
 
         static object o= new object();
         public static Singleton GetInstance()
         {
             if (s == null)
             { 
                 lock(o)
                 {
                     if (s == null)
                         s = new Singleton();
                 }
             }
 
             return s;
         }
 
     }
 }
 


2、静态初始化实现

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 
 namespace Singleton
 {
     class Singleton2
     {
 
         static readonly Singleton2 s= new Singleton2();
 
         private Singleton2() { }
 
         public static Singleton2 GetInstance()
         {
             return s;
         }
     }
 }

Client端代码


using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 
 namespace Singleton
 {
     class Client
     {
         static void Main(string[] args)
         {
             Singleton s1= Singleton.GetInstance();
             Singleton s2 = Singleton.GetInstance();
             if (s1 == s2)
             {
                 Console.WriteLine("s1与s2是两个相同的对象!");
             }
             Singleton2 s21 = Singleton2.GetInstance();
             Singleton2 s22 = Singleton2.GetInstance();
             if (s21 == s22)
             {
                 Console.WriteLine("s21与s22是两个相同的对象"); 
             }
         }
     }
 }

显示效果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值