单件模式

单件模式(Singleton) 适用于下面的情况:

逻辑上仅仅只有一个实例才可以保证逻辑的正确性。

通过共享减少内存的使用,作为应用中一些集中的统一数据机制存在。

减少因为频繁的构造过程带来应用上的性能损失

using System;
namespace VisionLogic.DesignPattern.Practice
...{
public class Singleton
...{
private static Singleton instance;
private Singleton() ...{ }
public static Singleton Instance
...{
get
...{
if (instance == null)
...{instance = new Singleton();
instance.data = 0;
}
return instance;
}
}
/**//// <summary>
/// 共享的实例数据
/// </summary>
private int data;
public int Data
...{
get ...{ return data; }
set ...{ data = value; }
}
}
}

using System;
using System.Diagnostics;
using VisionLogic.DesignPattern.Practice;
namespace VisionLogic.DesignPattern.Practice.Client
...{
class Program
...{
static void Main(string[] args)
...{
Singleton instance1 = Singleton.Instance;
Singleton instance2 = Singleton.Instance;
instance1.Data = 30;
Trace.WriteLine(instance2.Data);
instance2.Data = 15;
Trace.WriteLine(instance1.Data);
}
}
}
结果:
30
15

 

 

不要实现ICloneable接口或者继承自其相关的子类,否则客户程序可以跳过已经隐蔽起来的类构造函数,导致私有的Singleton() { } 部分的实效。

 

using System;
namespace VisionLogic.DesignPattern.Practice
...{
public class BaseEntity : ICloneable
...{
public object Clone()
...{
return this.MemberwiseClone();
}
}
public class Singleton : BaseEntity
...{
private static Singleton instance;
private Singleton() ...{ }
public static Singleton Instance
...{
get
...{
if (instance == null)
...{instance = new Singleton();
instance.data = 0;
}
return instance;
}
}
….
}
}

using System;
using System.Diagnostics;
using VisionLogic.DesignPattern.Practice;
namespace VisionLogic.DesignPattern.Practice.Client
...{
class Program
...{
static void Main(string[] args)
...{
Singleton instance1 = Singleton.Instance;
Singleton instance2 = (Singleton)instance1.Clone();
instance1.Data = 30;
Trace.WriteLine(instance2.Data);
instance2.Data = 15;
Trace.WriteLine(instance1.Data);
}
}
}
结果:
0
30

 

你可能感兴趣的:(模式)