一步一步掌握设计模式一(最简单的开始--单例模式^_^)
首先我得说我是个超级超级的菜鸟,逼自己写这个系列是为了让自己动手,是为了更好的掌握,所以,不要笑我的水平哦,呵呵!
老规矩,一个时钟类!
老规矩,一个时钟类!
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace Siglon
6 {
7 class Clock
8 {
9 private static Clock newClock;
10 private DateTime _shortTime;
11 private Clock()
12 {
13 _shortTime = DateTime.Now;
14 }
15 public DateTime ShortTime
16 {
17 get { return this._shortTime; }
18 }
19 public static Clock CreatClock()
20 {
21 if (newClock == null)
22 {
23 newClock = new Clock();
24 }
25 return newClock;
26 }
27 }
28 }
接下来是一个程序台的调用
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace Siglon
6 {
7 class Clock
8 {
9 private static Clock newClock;
10 private DateTime _shortTime;
11 private Clock()
12 {
13 _shortTime = DateTime.Now;
14 }
15 public DateTime ShortTime
16 {
17 get { return this._shortTime; }
18 }
19 public static Clock CreatClock()
20 {
21 if (newClock == null)
22 {
23 newClock = new Clock();
24 }
25 return newClock;
26 }
27 }
28 }
using System;
using System.Collections.Generic;
using System.Text;
namespace Siglon
{
class Program
{
static void Main(string[] args)
{
Clock c1 = Clock.CreatClock();
Console.Write(c1.ShortTime.ToShortTimeString()+"\n");
System.Threading.Thread.Sleep(3000);
Clock c2 = Clock.CreatClock();
Console.Write(c2.ShortTime.ToShortTimeString());
Console.ReadLine();
}
}
}
测试结果:两个时钟对象的时间都是一样的,证明成功拉!^_^
using System.Collections.Generic;
using System.Text;
namespace Siglon
{
class Program
{
static void Main(string[] args)
{
Clock c1 = Clock.CreatClock();
Console.Write(c1.ShortTime.ToShortTimeString()+"\n");
System.Threading.Thread.Sleep(3000);
Clock c2 = Clock.CreatClock();
Console.Write(c2.ShortTime.ToShortTimeString());
Console.ReadLine();
}
}
}
测试结果:两个时钟对象的时间都是一样的,证明成功拉!^_^