开发者

question on sealed properties

Hi i have 2 questions on the code below. Could you help to explain to me?

1) Why do we need sealed for this dataaccess class?

2) Why do we need singleton for this connectionstring?

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

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. Sealed class is to ensure no one inherits from this class. This also makes the class more performant due to JITer optimizations.

  2. You don't need an instance of the ConnectionString for every instance of the Repository object so it has been made static.


1)The sealed keyword is used to make it so the class cannot be extended. 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. The BooksRepository that is returned by the BookRepository() method is a singleton (or attempts to be really). 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. 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.

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. 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.


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.

In your case (from .net 2.0 onwards) it is effectively equivalent to (note the static class and removal of the private constructor)

  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] static BooksRepository _bookRepository = null;
  [ThreadStatic] static string connectionString;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜