简体   繁体   English

关于密封性能的问题

[英]question on sealed properties

Hi i have 2 questions on the code below. 您好我对以下代码有2个问题。 Could you help to explain to me? 你能帮我解释一下吗?

1) Why do we need sealed for this dataaccess class? 1)为什么我们需要密封这个数据访问类?
2) Why do we need singleton for this connectionstring? 2)为什么我们需要这个连接字符串的单例?

New Approach 新的方法

namespace DataAccess
{   
  //Singleton implementation to return the same BooksRepository   

  public sealed class Repository
  {

    static BooksRepository _bookRepository = null;
    static string connectionString;

    private Repository() { }

    public static void ConnectionString(string cs) { connectionString = cs; }

    public static BooksRepository BookRepository(Boolean create)
    {
      if (connectionString == null) 
        throw new ApplicationException("Need to set connection string for Repository");
      if (!create && _bookRepository != null) return _bookRepository;
      else
      {
        _bookRepository = new BooksRepository(connectionString);
        return _bookRepository;
      }
    }

  }
}

Apply in UI 在UI中应用
Books = Repository.BookRepository(false).GetAllBooks();

-------------------UPDATE ------------------------------------------------ -------------------更新------------------------------ ------------------
** Old Approach **老方法

This is what i practice for most of my projects. 这就是我为大多数项目练习的内容。 Isn't it more easier and simple than doing declaring the singleton concept as the above? 这不是比宣布单身概念更容易和简单吗?

public partial class ZebraDataContext
{
    public ZebraDataContext()
        : base(ConfigurationManager.ConnectionStrings["ZebraConnString"].ToString())
    {
    }
}

In my Class 在我的课堂上

  public void Add()
    {
        using (TransactionScope ts = new TransactionScope())
        {
            using (ZebraDataContext db = new ZebraDataContext())
            {
                try
                {
                    db.Stocks.InsertOnSubmit(this);
                    db.SubmitChanges();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex);
                    Logger.Error(typeof(Stock), ex.ToString());
                    throw;
                }
            }
            ts.Complete();
        }
    }

1)The sealed keyword is used to make it so the class cannot be extended. 1)使用sealed关键字使其无法扩展。 Whoever wrote the class decided that they needed to prevent people from extending and modifying the behavior. 编写课程的人决定他们需要阻止人们扩展和修改行为。 Without a greater context it is impossible to answer the question in any more detail than that. 没有更大的背景,就不可能更详细地回答这个问题了。

2) ConnectionString is not a singleton, it is static. 2) ConnectionString不是单例,它是静态的。 The BooksRepository that is returned by the BookRepository() method is a singleton (or attempts to be really). BooksRepository由所述返回BookRepository()方法是单(或尝试是真的)。 Again without a greater context it is impossible to say if it needs to be a singleton. 再一次没有更大的背景,就不可能说它是否需要单身。 The reason you would use a singleton in this situation is if you want to ensure that everywhere in the application uses the same BooksRepository object. 在这种情况下使用单例的原因是,如果要确保应用程序中的任何位置使用相同的BooksRepository对象。 I'm assuming that the writer was trying to ensure the same connection string would be used to connect to the BooksRepository throughout the application. 我假设作者试图确保在整个应用程序中使用相同的连接字符串连接到BooksRepository

However, looking at how this is written it does not really obey the singleton pattern. 然而,看看这是如何写的,它并没有真正服从单身模式。 It appears you can create multiple BooksRepository by specifying a true for create in the BookRepository() method. 看来你可以通过在BookRepository()方法中为create指定true来创建多个BooksRepository Any existing references to the previous objects would still exist and not change. 对先前对象的任何现有引用仍将存在且不会更改。 If the connection strings were changed between calls to BookRepository() then there would be different connection strings through the application. 如果在对BookRepository()调用之间更改了连接字符串,则应用程序中将存在不同的连接字符串。

  1. Sealed class is to ensure no one inherits from this class. 密封类是为了确保没有人从这个类继承。 This also makes the class more performant due to JITer optimizations. 由于JITer优化,这也使类更具性能。

  2. You don't need an instance of the ConnectionString for every instance of the Repository object so it has been made static. 对于Repository对象的每个实例,您不需要ConnectionString的实例,因此它已经变为静态。

I would say that the code you see is the pre .Net 2.0 way of creating a static class where the class cannot be instantiated or inherited. 我会说你看到的代码是pre .Net 2.0创建静态类的方法,其中类不能被实例化或继承。

In your case (from .net 2.0 onwards) it is effectively equivalent to (note the static class and removal of the private constructor) 在你的情况下(从.net 2.0开始)它实际上等同于(注意静态类和删除私有构造函数)

  public static class Repository
  {

    static BooksRepository _bookRepository = null;
    static string connectionString;

    public static void ConnectionString(string cs) { connectionString = cs; }

    public static BooksRepository BookRepository(Boolean create)
    {
      if (connectionString == null) 
        throw new ApplicationException("Need to set connection string for Repository");
      if (!create && _bookRepository != null) return _bookRepository;
      else
      {
        _bookRepository = new BooksRepository(connectionString);
        return _bookRepository;
      }
    }
  }

Whether you should be using static for connections is another story. 是否应该使用静态连接是另一个故事。 I would say at a minimum use [ThreadStatic] on your connection so it can support concurrency (multithreaded access to their own connection). 我会说至少在你的连接上使用[ThreadStatic] ,所以它可以支持并发(对自己的连接的多线程访问)。

  [ThreadStatic] static BooksRepository _bookRepository = null;
  [ThreadStatic] static string connectionString;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM