C#项目中常用到的设计模式

发表于:2016-6-30 11:59

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:禅宗花园...迷失的佛    来源:51Testing软件测试网采编

#
DoNet
分享:
  1. 引言
  一个项目的通常都是从Demo开始,不断为项目添加新的功能以及重构,也许刚开始的时候代码显得非常凌乱,毫无设计可言。但是随着项目的迭代,往往需要将很多相同功能的代码抽取出来,这也是设计模式的开始。熟练运用设计模式应该是每一个软件开发人员的必备技能。今天给大家介绍几个常用的设计模式。
  2. 单例模式
  单例模式恐怕是很多开发人员最先接触到的模式之一,可以认为就是一个全局变量。它的初始化过程无非就是一开始就new 一个instance,或者惰性初始化等需要用到的时候new 一个instance。这里需要注意的是在多线程情况下new一个instance。通常加上lock 可以解决问题。这里我们利用C# 的系统函数 Interlocked.CompareExchange
internal class SingletonOne
{
private static SingletonOne _singleton;
private SingletonOne()
{
}
public static SingletonOne Instance
{
get
{
if (_singleton == null)
{
Interlocked.CompareExchange(ref _singleton, new SingletonOne(), null);
}
return _singleton;
}
}
}
  3. 迭代器模式
  迭代器模式也是用的比较多的一种,通常见于C#的内置容器数据结构 List,Stack等等,为了便于遍历容器内元素。这里给出一个简单版的Stack实现
internal class Stack<T> : IEnumerable<T>, IEnumerable
{
private T[] _array;
private int _index;
private const int DefaultSize = 4;
public Stack(int size)
{
var sized = size > 0 ? size : DefaultSize;
this._array = new T[sized];
this._index = 0;
}
public int Count
{
get { return this._index; }
}
public Stack(IEnumerable<T> data) : this(0)
{
var enumrator = data.GetEnumerator();
while (enumrator.MoveNext())
{
var item = enumrator.Current;
this.Push(item);
}
}
public void Push(T item)
{
if (this._index < this._array.Length)
{
this._array[this._index++] = item;
}
else
{
var newLength = this._array.Length << 1;
T[] newArray = new T[newLength];
Array.Copy(this._array, newArray, this.Count);
this._array = newArray;
this.Push(item);
}
}
public T Pop()
{
if (this.Count <= 0)
{
throw new ArgumentOutOfRangeException("pop");
}
else
{
this._array[this._index] = default(T);
return this._array[--this._index];
}
}
public T Get(int index)
{
if (this.Count <= index)
{
throw new ArgumentOutOfRangeException("Get");
}
else
{
return this._array[index];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return new StackEnumerator<T>(this);
}
}
  Stack 的 迭代器内部实现:
internal class StackEnumerator<T> : IEnumerator<T> , IEnumerator
{
private Stack<T> _stack;
private int _index;
public StackEnumerator(Stack<T> stack)
{
this._stack = stack;
this._index = -1;
}
public bool MoveNext()
{
this._index++;
return this._index < this._stack.Count;
}
public void Reset()
{
this._index = -1;
}
object  IEnumerator.Current
{
get { return this.Current; }
}
public T Current
{
get { return this._stack.Get(this._index); }
}
public void Dispose()
{
this._stack = null;
}
}
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号