Showing posts with label Design patterns. Show all posts
Showing posts with label Design patterns. Show all posts

Monday, January 30, 2012

Creating Objects Using Factory Methods

Consider static factory methods instead of constructors

Normally when we use constructor methods(new key word) to create instances of a class. And in post i am going to explain another way of create object which is static factory methods.For an example we can take one of factory method implemented in java.lang.Boolean.
 
public static Boolean valueOf(boolean b){
 return b? Boolean.TRUE : Boolean.FALSE;
}

Providing factory method to create objects rather than using constructors has both advantaged and disadvantages.
Advantages of having Factory methods to create instances 

  • Factory methods have a valid name 
Imaging you have a Shape class and it has a constructor which accept one int parameter which is the number of edges.If parameter is 3 it returns a triangle.So the client code which use this constructor is not too clear since constructor method does not make a sense about the object which is going to retrieve. But if we have a static factory method called getTriangle() which returns a triangle shape instance, it would be more readable than having a constructor method. 

  • Do not need to create new object in each time 
This is the implementation of singleton pattern. This technique is very useful is cases of cost of creating an instance is too high and where we can share a single object. One of the advantage of using this concept is we don't need equals( ) method for comparisons and we can simple check the equality by == operator.

  • Factory methods can returns any sub type of their return type 
One application of this flexibility is that an API can return object without making their classes public.For an example look at the java.util.Collections. In this case interfaces provide return types for static factory methods. And those static factory methods are put in a non instantiable class. 

  • Reduce the overhead of creating parameterized type instances 



Instead of this kind of constructor methods we can have a factory method which can be reusable with less effort. 



Disadvantages of having Factory methods to create instances 
  • It is hard to distinguish factory static method form other available static methods
  • Non public classes cannot be sub classed(If we have factory method to create instance then we can make that class a private) 

Thursday, January 12, 2012

Where We Need Dependency Injection

Recently I was working with a .Net project which uses Entity Framework .It has a layered architecture where we can find following separate layers.

 Service layer (Eg: Order Services)
 Domain Layer (Eg: Domain entities like book,Order)
 Infrastructure Layer (Repositories, DBContexts,Unit of work pattern Impl) 
 MVC3 Client (Presentation Layer)

 In my case Service methods are called in controller classes in MVC3 client package(according to the mvc pattern). MVC3 client package and Service layer are implemented by two developers .In this case MVC3 client project does not know much details about Service package and all he knows about the service package is that he can get some services by passing values to the service method.

 Eg: Lets say in service package we are having BookService class which is offering borrow book functionality. Then from the controller’s point of view what he wants to do is borrow a book by just passing the book id. Simply the controller doesnot want to know the underline functionality of Bookservice class (DBcontext,repositories,unitofworks)

 But according to the implementation of the BookService class it has only one constructor which has all its dependencies which are unknown by controller (MVC3 client project). Then when it comes to instance creation of BookService class we may end up with big issue. To solve this issue we need to inject dependencies of BookService by using a third party which knows about object creation of BookService class. This is called contractor dependency injection .Actually what controller wants to know is how to use bookservice object instead of knowing how to create BookService object.

Following are the structure of CSharp classes  I was explaining above.

  
public class BookService : IBookService
{
       public IBookRepository _bookrepository;
       public IUnitOfWork _unitOfWork;
    public BookService(IBookRepository bookRepository,IUnitOfWork unitOfWork)
    {
         _bookrepository = bookRepository;
         _unitOfWork = unitOfWork;
     }
    public Book BorrowBook(int bookId)
   {
         //Logic Goes Here
    }
}

Public class BookController
{
   IBookService _bookService;
    public BookController(IBookService bookService)
   {
           _bookService = bookService;
    }

   //Borrow book HTTP POST 
   public void BorrowBook(int bookId)
   {
        _bookService.BorrowBook(bookId);
    }
}

Here We can see we have not create object of BookService so BookController does not need to know about BookService dependencies. In order to get this working we need to use third party dependency injection tools. For .Net project i would recommend winsor container which is more flexible to use. Following tutorial illustrate how to use winsor for dependency injection.

http://stw.castleproject.org/Windsor.MainPage.ashx