Learn.Develop.Share

Twitter












Patterns:Factory

Since I have already mentioned Factory in a post, its time we should talk about the same. Factory should get the respect it deserves because its worth it.
 Intent
Defines an interface for creating an object, but lets subclasses decide which of those to instantiate.
 Scenario
 Say we need to implement a way to create Accounts. Now, there are different kinds of Account,
a.) Savings Account - Acts as a Normal, but allows you to withdraw only when you are not taking the balance below the minimum stipulated balance.
a.) i.) Salaried Savings Account - Same as Savings Account but minimum balance can be 0.
b.) Current Account.- Can allow you to go till a -ve balance, only for traders
 
As you can see, the difference in limit and the difference in Withdrawl Strategies. There are many other business rules, but for the context of the Problem, we would like to keep it simple. But one essential question is, why do we need to think so much, we just need to be able to create Savings Account, Salaried Savings Account and Current Account ?
 
Well, the bank says we want to keep a hook for bringing in new types of Account in Near future. There you have it, Business as usual. So how do you structure the code, I can think of, I would create an Account Class, where the Deposit would be having a implementation since, its function is just to add money to the account. But as for the Withdraw method I would leave it as abstract, because, it depends on the type of Account you are operating it. Its a stronger relationship.
 
 
In this scenarios, we generally prefer the factory pattern where in, if a new type of Account is introduced tommorow, we can easily add a new subclass of the AccountFactory class and bring in support for a new kind of account.
 Let me just substantiate, what I just wrote.
 
 
 
So as you can see from the above diagram, the responsibility of creation of CurrentAccount lies in CurrentAccountFactory and like wise for SavingsAccount the SavingsAccountFactory. Say we introduce a new Account Class we just need to introduce a new AccountFactory subclass which will take care of instantiating it properly.
 
There are two versions of a Factory pattern:
 
1. Static Factory. There are no subclasses, rather there is a single static method that takes in a parameter and creates a appropriate instance of the product. This works when the frequency of adding a product is low and it can survive a compilation.
 
2. Instance Factory. This generally works in conjunction with Reflection as in Java/.Net. and this works better when the chances of adding a product is high and we do not want to re-compile the whole code base.
 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Feedback

No comments posted yet.