C# 设计模式 - 单例模式 演示
生活随笔
收集整理的這篇文章主要介紹了
C# 设计模式 - 单例模式 演示
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
using?System;
using?System.Collections.Generic;
using?System.Linq;
using?System.Text;
using?System.Threading.Tasks;
namespace?DBImportTool.Sgile
{
????//第一種單例模式Demo
????public?class?A
????{
????????private?volatile?static?A?_instance?=?null;
????????private?static?readonly?object?lockHelper?=?new?object();
????????private?A()?{?}
????????public?static?A?CreateInstance()
????????{
????????????//?判斷如果沒有實例過,則進(jìn)行實例化創(chuàng)建.
????????????//?瞬間觸發(fā)量不高的網(wǎng)站,不需要此判斷步驟.
????????????if?(_instance?==?null)
????????????{
????????????????//鎖機(jī)制.防止重復(fù)實例化.
????????????????lock?(lockHelper)
????????????????{
????????????????????if?(_instance?==?null)
????????????????????{
????????????????????????_instance?=?new?A();
????????????????????}
????????????????}
????????????}
????????????return?_instance;
????????}
????}
????//第二種單例模式Demo
????public?sealed?class?B
????{
?
????????B()?{?}
????????public?static?B?GetInstance()
????????{
????????????return?B1.b;
????????}
????????class?B1
????????{
????????????static?B1()
????????????{
????????????}
????????????internal?static?readonly?B?b?=?new?B();
????????}
????}
}
using?System.Collections.Generic;
using?System.Linq;
using?System.Text;
using?System.Threading.Tasks;
namespace?DBImportTool.Sgile
{
????//第一種單例模式Demo
????public?class?A
????{
????????private?volatile?static?A?_instance?=?null;
????????private?static?readonly?object?lockHelper?=?new?object();
????????private?A()?{?}
????????public?static?A?CreateInstance()
????????{
????????????//?判斷如果沒有實例過,則進(jìn)行實例化創(chuàng)建.
????????????//?瞬間觸發(fā)量不高的網(wǎng)站,不需要此判斷步驟.
????????????if?(_instance?==?null)
????????????{
????????????????//鎖機(jī)制.防止重復(fù)實例化.
????????????????lock?(lockHelper)
????????????????{
????????????????????if?(_instance?==?null)
????????????????????{
????????????????????????_instance?=?new?A();
????????????????????}
????????????????}
????????????}
????????????return?_instance;
????????}
????}
????//第二種單例模式Demo
????public?sealed?class?B
????{
?
????????B()?{?}
????????public?static?B?GetInstance()
????????{
????????????return?B1.b;
????????}
????????class?B1
????????{
????????????static?B1()
????????????{
????????????}
????????????internal?static?readonly?B?b?=?new?B();
????????}
????}
}
轉(zhuǎn)載于:https://www.cnblogs.com/mcqueen/p/4023768.html
總結(jié)
以上是生活随笔為你收集整理的C# 设计模式 - 单例模式 演示的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Web结构组件
- 下一篇: c# char unsigned_dll