【问题标题】:Optimize my Code logic without singletion在没有单例的情况下优化我的代码逻辑
【发布时间】:2015-07-29 16:54:40
【问题描述】:
 public interface IHandler
    {
        List<string> Run();
    }

public class Base 
{

    void methodA();
}

public Class Der1 : Base , IHandler
{
     List<string> Run()
     { //Generate huge records
     }
}

public Class Der2 : Base , IHandler
{
     List<string> Run()
     {//Generate huge records
     }
}

public Class Der3 : Base , IHandler
{
     List<string> Run()
     {//Generate huge records
     }
}

目前 Run() 正在所有派生类中执行并生成相同的记录集。我希望对此进行优化。

将 Run() 中的 RecordGeneration 过程移动到一个公共类/函数中并执行一次并准备必要的记录。所有的 Derived 类都会使用这个“RecordGeneration”来获取已经生成的记录。

注意:我无法实现单例模式。

【问题讨论】:

  • Code Review 会不会更好?
  • 为什么IHandler 没有在Base 中实现?

标签: c# .net performance singleton


【解决方案1】:

你可以使用Lazy&lt;T&gt;:

private Lazy<List<string>> l;

public Der1
{
    l = new Lazy<List<string>>(() => Run());
}

public List<string> ResultOfRun
{
    get
    {
         return l.Value();
    }
}

为了扩展我最初的答案,如果该方法在所有方法中具有相同的输出,您可以这样做:

public class Base
{
    private Lazy<List<string>> l =  new Lazy<List<string>>(() => RunStatic());

    private static List<string> RunStatic()
    {
        //
    }

    public List<string> ResultOfRun
    {
        get
        {
             return l.Value();
        }
    }

    void methodA();
}

那么你只需要在Run中调用它,如果它实现了接口,它可能在基类中:

public Class Der1 : Base , IHandler
{
     List<string> Run()
     {
         return this.ResultOfRun;
     }
}

【讨论】:

  • 看起来l 应该是静态的并移动到Base,因为所有后代的结果都是相同的。
  • l 不能是静态的,因为它使用实例变量。其次,基类没有实现所需的接口,而我确实更喜欢它。
  • 啊,好吧。现在我明白你的意思了。是的,最好将它移到那里并使其静止。
  • 你能简单介绍一下我的例子吗?,我无法理解你在讨论什么......
  • @user1581317 好的。更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多