微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#设计问题

我开始设计一个小应用程序,并有一些与架构相关的问题.

我有一些基本实体,我愿意建模 – 存储库和指标.

存储库基本上是使用存储库模式的外观,它可以使用某个数据库持有者检索/存储任意实体(现在它是NHibernate驱动的,但我想这实际上并不重要).

指标可以称为我的应用程序的逻辑核心.它用于组合抽象值和实现该值的确切时间(因此它在值 – 时间对上形成和操作).

我愿意让这个指标尽可能通用,但我认为我目前的解决方案是一个很大的失败:)

请参阅以下代码块:

public interface IIndicator<T>
{
    IEnumerable<T> RetrieveValues(DateTime start,DateTime end);
}

// Should also have something like indicator wrapper / proxy stub here - anything
// that represents the 'IIndicator' interface acts through that proxy and
// caches the evaluated data using it.

这是实现指标的基本尝试(现在这实际上可以被视为模拟):

public class Indicator<TValue> :
    // Self-referencing generic parameter.
    IIndicator<Indicator<TValue>.TimestampProxy>
{
    // Proxy,which is used to add the timestamp to
    // every indicated value.
    public class TimestampProxy
    {
        public TValue Value;
        public DateTime Time;

        public TimestampProxy(DateTime time,TValue value)
        {
            Time = time;
            Value = value;
        }
    }

    private readonly IRepository repository;

    public Indicator(IRepository repository)
    {
        this.repository = repository;
    }

    public IEnumerable<TimestampProxy> RetrieveValues(DateTime start,DateTime end)
    {
        // Note the custom time stamp comparation in the lambda
        // expression. Comparation includes the 'start' and 'end' limits.
        IQueryable<TimestampProxy> queryable = repository.Retrieve<TimestampProxy>(
            x => x.Time.Compareto(start) >= 0 && x.Time.Compareto(end) <= 0);

        return queryable.ToList();
    }
}

现在 – 这可能看起来很好,但我绝对相信使用的TimestampProxy真的很邪恶.

它也使事情难以理解(例如,方法签名IEnumerable< TimestampProxy> RetrieveValues(…)可能会导致来自检查代码的人的“wtf?!”短语).

不幸的是,我无法提出更好的解决方案/全局重新设计 – 你能建议我怎么做或者只是告诉一些关于应该如何完成这种功能的想法?

谢谢.

解决方法

如何将RetrieveValues方法重构为Repository本身,并使用更简单的Indicator类,它基本上替换了TimestampProxy类.

public class Indicator<T>
{
     public DateTime Timestamp { get; set; }
     public T Value { get; set; }
}


public class Repository
{

     public IEnumerable<Indicator<T>> RetrieveIndicators<T>( DateTime start,DateTime end )
     {
          // determine table to query based on type T
          // query and convert objects to Indicator<T>
          // return collection
     }
}

困扰我的一件事是,在使它成为通用的时候,你已经失去了与DB表的连接.简单地定义一个所有特定DB对象实现的接口并使用部分实现将实际“值”映射到Value属性可能更好.

public interface Indicator<T>
{
     DateTime Timestamp { get; }
     T Value { get; }
}

public partial class TemperatureIndicator : Indicator<double>
{
     public double Value { get { return this.Temperature; } }
}

现在让您的存储库实现返回每种类型对象的方法 – 可以用作(在.NET 4中或转换为较低版本)接口类型的对象以进行常见操作.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐