5.1将Timer类映射成代码
public delegate void TimerHandler();
public class Timer//单实例类Timer
{
private static Timer instance; //静态实例引用
private int timeRemaining;//剩余时间
private bool isOn; //定时器开启状态指示器
//用于判断外界条件(比如门的闭和与否,可以扩展到其他外界条件)是否允许定时器计时。
//一旦计时即微波炉处于正常工作状态。比如在此例中用来判断门是否关闭。
private bool isReady;
private bool isSuspended; //定时器挂起状态指示器
private const int TIMEINTERVAL = 1000; //定时单位
private System.Timers.Timer calculagraph; //计时器
//定时器启动停止事件
public event TimerHandler TimerOn;
public event TimerHandler TimerOff;
//定时器暂停继续事件
public event TimerHandler TimerPause;
public event TimerHandler TimerResume;
public event TimerHandler TimerExpired; //定时器到时事件
public event TimerHandler TimerCount;//定时器剩余时间改变引发的事件
private Timer()//私有的构造函数,不能从类外部进行构造
{
this.timeRemaining = 0; //默认剩余时间为0秒
this.isOn = false; //默认定时器为停止状态
this.isReady = true; //默认外界条件成立,因为初始状态时门为关闭状态
this.isSuspended = false; //默认定时器没有挂起
//初始化计时器
this.calculagraph = new System.Timers.Timer(TIMEINTERVAL);
calculagraph.Elapsed += new System.Timers.ElapsedEventHandler(this.timing);
}
public static Timer GetInstance()//返回唯一实例
{
if (instance == null)
{
instance = new Timer();
}
return instance;
}
public int GetTimeRemaining()//返回定时器的剩余时间
{
return this.timeRemaining;
}
public bool GetIsOn()//返回定时器的开启状态
{
return this.isOn;
}
public bool GetIsReady()//返回定时器外部状态成立与否
{
return this.isReady;
}
public bool GetIsSuspended()//返回定时器的挂起状态
{
return this.isSuspended;
}
public void SetIsReady(bool isReady) //设定定时器外部状态成立与否
{
this.isReady = isReady;
}
private void startTiming()//计时器开始计时,并且引发Elapse事件
{
calculagraph.Start();
}
private void stopTiming()//计时器停止计时,并且停止引发Elapse事件
{
calculagraph.Stop();
}
//计时操作,此操作注册到calculagraph.Elapse事件,每次触发Elapse事件都会调用此操作
private void timing(object source, ElapsedEventArgs e)
{
//正常情况下每次触发Elapse事件,剩余时间会递减
//当设定时间递减至0时,触发TimerExpired事件,通知所有预定定时器到时事件的监听者,//并停止计时器工作
if (timeRemaining > 0 && isOn && isReady && !isSuspended)
{
timeRemaining--;
TimerCount();//通知外部监听者更新时间
}
else if (isOn && isReady && !isSuspended)
{
this.timeExpired();
上一页 [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] ... 下一页 >>