回头看singleton(单件)

回头望,已过万重山

出来工作有段时间拉,用设计模式也有一段时间了,这几天有空就整理一下。先说singleton(单件)吧。

刚学设计模式的时候(我开始是学c++和做j2me出身的)

public class Sample

{

private static Sample _Instance;

private Sample()

{

}

public static Sample GetInstance()

{

if (null == _Instance)

{

_Instance = new Sample();

}

return _Instance;

}

}

学会用get和set以后:

public class Sample

{

private static Sample _Current;

private Sample()

{

}

public static Sample Current

{

get

{

if (null == _Current)

{

_Current = new Sample();

}

return _Current;

}

}

}

学会多线程操作以后:

public class Sample

{

private static Sample _Current;

private static object _threadlook = new object();

private Sample()

{

}

public static Sample Current

{

get

{

if (null == _Current)

{

lock (_threadlook)

{

if (null == _Current)

{

_Current = new Sample();

}

}

}

return _Current;

}

}

}

学会用MSIL以后:

public class Sample

{

private static Sample _Current;

private Sample()

{

}

public static Sample Current

{

get

{

if (null == _Current)

{

lock (typeof(Sample))

{

if (null == _Current)

{

_Current = new Sample();

}

}

}

return _Current;

}

}

}

当然还有根据具体解决环境中添加了相应的关键字和相关的语句,大概数了一下,还有九种写法。由于环境描述的问题。在此略过。

现在回头看这些代码的写法,感触万分,当时每个阶段写出第一次这样的代码的时候,感觉开心极了,很成功的感觉,现在回头看,学海无涯,当初是多幼稚啊,想发笑。不过也体会到一句话:学过其他语言,只能很快的学会另一种语言,但是要弄懂、精通这种语言,还是要花很大功夫。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值