拆分复杂的if-else判断分支 把这些逻辑放在类里面完成
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPytternDemo
{
public interface ITime
{
void SayHello();
}
public abstract class BaseTime : ITime
{
public int Time { get; set; }
public abstract void SayHello();
public BaseTime(int t)
{
this.Time = t;
}
}
public class Morning : BaseTime
{
public Morning(int t) : base(t) { }
public override void SayHello()
{
if (this.Time >= 7 && this.Time < 12)
{
Console.WriteLine("good morning,sir" + " time is {0}" , this.Time);
}
else
{
new Noon(this.Time).SayHello();
}
}
}
public class Noon : BaseTime
{
public Noon(int t) : base(t) { }
public override void SayHello()
{
if (this.Time >= 12 && this.Time <= 13)
{
Console.WriteLine("have a nice lunch ,sir" + " time is {0}" , this.Time);
}
else
{
new AfterNoon(this.Time).SayHello();
}
}
}
public class AfterNoon : BaseTime
{
public AfterNoon(int t) : base(t) { }
public override void SayHello()
{
if (this.Time > 13 && this.Time <= 18)
{
Console.WriteLine("good afternoon,sir" + " time is {0}" , this.Time);
}
else
{
new Night(this.Time).SayHello();
}
}
}
public class Night : BaseTime
{
public Night(int t) : base(t) { }
public override void SayHello()
{
if (this.Time > 18 && this.Time <= 24)
{
Console.WriteLine("good evening,sir" + " time is {0}" ,this.Time);
}
else
{
new DeepNight(this.Time).SayHello();
}
}
}
public class DeepNight : BaseTime
{
public DeepNight(int t) : base(t) { }
public override void SayHello()
{
if (this.Time >= 0 && this.Time < 7)
{
Console.WriteLine("have a good sleep,sir" + " time is {0}" ,this.Time);
}
else
{
Console.WriteLine("oh,unexpected time {0},", this.Time);
}
}
}
}
static void Main(string[] args)
{
BaseTime bt = new Morning(1);
bt.SayHello();
bt.Time = 8;
bt.SayHello();
bt.Time = 12;
bt.SayHello();
bt.Time = 14;
bt.SayHello();
bt.Time = 21;
bt.SayHello();
Console.ReadLine();
}