假设我们有
public interface ITimestampProvider
{
DateTime GetTimestamp();
}
和一个消耗它的类
public class Timestamped
{
private ITimestampProvider _timestampProvider
public Timestamped(ITimestampProvider timestampProvider)
{
// arg null check
_timestampProvider = timestampProvider;
}
public DateTime Timestamp { get; private set; }
public void Stamp()
{
this.Timestamp = _timestampProvider.GetTimestamp();
}
}
和一个默认实现:
public sealed class SystemTimestampProvider : ITimestampProvider
{
public DateTime GetTimestamp()
{
return DateTime.Now;
}
}
引入这个构造函数是有帮助还是有害?
public Timestamped() : this(new SystemTimestampProvider())
{}
这是一个普遍的问题,即时间戳不是有趣的部分。