SingletonProvider 实现代码

 1设计模式Singleton的Provider实现using System;
 2设计模式Singleton的Provider实现using System.Collections.Generic;
 3设计模式Singleton的Provider实现using System.Text;
 4设计模式Singleton的Provider实现using System.Reflection;
 5设计模式Singleton的Provider实现
 6设计模式Singleton的Provider实现namespace AIO.DesignPattern.Singleton
 7

取消采用第20行是因为'Activator.CreateInstance<T>()'调用必须实现Public的构造函数

采用现在方式有两种好处:一是将构造函数声明为私有或受保护避免多种方式调用,另一种方式是将构造函数声明为公有使得既可以单件又可以多件使用(本人觉得有时候很有用,尤其是代码作为类库时)

线程安全版本代码如下:

 1设计模式Singleton的Provider实现using System;
 2设计模式Singleton的Provider实现using System.Collections.Generic;
 3设计模式Singleton的Provider实现using System.Text;
 4设计模式Singleton的Provider实现using System.Reflection;
 5设计模式Singleton的Provider实现
 6设计模式Singleton的Provider实现namespace AIO.DesignPattern.Singleton
 7

 

单元测试代码如下:

 1设计模式Singleton的Provider实现using Microsoft.VisualStudio.TestTools.UnitTesting;
 2设计模式Singleton的Provider实现using System;
 3设计模式Singleton的Provider实现using System.Text;
 4设计模式Singleton的Provider实现using System.Collections.Generic;
 5设计模式Singleton的Provider实现using AIO.DesignPattern.Singleton;
 6设计模式Singleton的Provider实现namespace AIO.UnitTest
 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

相关文章: