SingletonProvider 实现代码
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using System.Reflection;
5
6
namespace AIO.DesignPattern.Singleton
7
2
3
4
5
6
7
取消采用第20行是因为'Activator.CreateInstance<T>()'调用必须实现Public的构造函数
采用现在方式有两种好处:一是将构造函数声明为私有或受保护避免多种方式调用,另一种方式是将构造函数声明为公有使得既可以单件又可以多件使用(本人觉得有时候很有用,尤其是代码作为类库时)
线程安全版本代码如下:
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using System.Reflection;
5
6
namespace AIO.DesignPattern.Singleton
7
2
3
4
5
6
7
单元测试代码如下:
1
using Microsoft.VisualStudio.TestTools.UnitTesting;
2
using System;
3
using System.Text;
4
using System.Collections.Generic;
5
using AIO.DesignPattern.Singleton;
6
namespace AIO.UnitTest
7
2
3
4
5
6
7
应用代码简单到只有一行如下:
SingletonProvider<SomeClass>.Instance.doSomething();
ok 今天就到这里 有时间会将其扩展实现单件/多件扩展的 Provide(Pooling FixedSize MaxSize etc.)
If you have all DesignPattern's Provider, you'll look the technology is just simple!
the Art of programing