Tutorial List
Home
Interview Questions
Interview
Interview Questions
Links
Web Home
About Us
Showing posts with label design pattern. Show all posts
Showing posts with label design pattern. Show all posts

MVC Pattern




MVC pattern is the first pattern a Java professional heard in his career. This is most widely used patterns. We all use   MVC pattern in our work, but when it comes to define it in interview, it become perplex to express something we use very often. Here we will discuss theoretical aspects of MVC pattern as Implementation will be covered in Struts,

What is MVC Pattern:
MVC is Model View Controller pattern. 
Model: Model is back end of application i.e. DB/DAO layer. This includes   db handling part of your application.
View: View is front end of your application. Everything that end user   interact with, is view. View is implemented using JSP, Servelet, HTML, PHP pages.
Controller: Controller is central component which decide flow of your application. Each request is passed to controller and controller, on looking request type, decides how to handle the request. View  and Model interacts with each other through Controller. When end user make some request by clicking some link on view, a request is passed to Controller and Controller then passes the request to Model. Model retrieves the required data from DB and return to Controller, which then pass the response to View where end user see the result of his action.
Thats how MVC patterns works.
Why to Use MVC:
MVC patterns is used to ensure separation of layer of concern. This separate UI codes from application logic and db access code. So UI people can work on UI part and application programmer can work on business logic while db programmer can write db access code with out bothering about other two team. End of day, they all can assemble their work and project will be ready much before deadline.
Second advantage is, when there is some change needed in any of these layer (UI, Business, DB), other layer remains untouched so there are less chances of rational bugs.
Another advantage is, all the application flow is controlled from one location by controller. This way you can predict the behavior of application in better way and this brings a great flexibility to the application.

I guess you must have got what MVC pattern is. In case of any query, feel free contact me at mohit.amour@gmail.com.

Thanks,
Mohit Singh

Decorator Pattern - Make Your Design Flexible

the decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing object dynamically. The decorator pattern is an alternative to subclassing. Inheritance adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at runtime for individual objects.

Decorator Pattern V/S Inheritance
Inheritance is a powerful feature of OOPS but and it makes design flexible, but it introduces extra lines of codes as you need to create a new subclass for each new behavior. For limited number of subclasses, Inheritance will go well but if functionality increase number of subclass increase as well and it makes design more and more complex.

Lets Take a break and have a coffee:
In coffee menu, we have a base class Coffee. I ask cofeemaker to gimme coffee with milk so he created a subclass MilkCoffee. My friend ask him for coffee with no sugar (Yuk)...so he created another subclass of coffee, so now total we have following classes,
  1. Coffee
  2. CoffeeWithSugar
  3. MilkCoffeeMilk
  4. CoffeeWithSugar
till now, every thing goes fine as coffeemaker create a new subclasss of coffee for each new kind of order, when I went to pay bill, two people came and one asked for coffee with cream and second asked for extra strong coffee.
Now coffee maker has to create following subclass of coffee,
  1. Coffee
  2. CoffeeWithSugar
  3. MilkCoffee
  4. MilkCoffeeWithSugar
  5. CoffeewithCream
  6. CoffeeWithSugerAndCream
  7. MilkcoffeeAndCream
  8. MilkcoffeeWithSugerAndCream
  9. ExtraStongCoffee
  10. ExtraStrongCoffeewithSugar
  11. ExtraStrongMilkCoffee
  12. ExtraStrongMilkCoffeeWithSugar
  13. ExtraStrongCoffeewithCream
  14. ExtraStrongCoffeeWithSugarAndCream
  15. ExtraStrongMilkcoffeeAndCream
  16. ExtraStrongMilkcoffeeWithSugarAndCream
God...he need to handle this number of subclass in his Coffee Application. I was really worried about his application design as when number of demands grow with time, he will end up with Himalaya of subclass as each new request with lead to creation of "N" new subclass where N is number of existing classes. ...

Now,Lets think about Decorator,
For each new request he just need to create one decorator and he can decorate any kind of coffee with that decorator irrespective of number of existing classes,
Like, he can create
Cream Decorator and he can decorate any coffee whether it is Milk Coffee or Extra Strong coffee...
I think we has a lot of theoretical discussion, lets move to example codes as we understand best with simple code snippet,
***********************************************************************
/*Your base coffee class. Here we define only basic coffee making procedure*/
class Coffee
{
public void makeCoffee() {
//secret coffee making procedure
}
}

/*Here we create a base decorator with no custom behavior*/
class CoffeeDecorator extends Coffee
{
protected Coffee objDecoratedCoffee = null;
CoffeeDecorator(Coffee objCoffee) {
this.objDecoratedCoffee = objCoffee;
}
}
/*Here we create Decorator to make Sugared Coffee. This decorator will extends CoffeeDecorator and over-ride the parent class's makeCoffee() method to add sugar to coffee*/
class SugarDecorator extends CoffeeDecorator
{
SugarDecorator(Coffee objCoffee) {
super(objCoffee);
}

public void makeCoffee() {
objDecoratedCoffee.makeCoffee();
addSugar();
// now your sugared coffee is ready
}

protected void addSugar()
{
// add sugar procedure
}
}

/*Here we create Cream Decorator which is similar to SugarDecoarator. The only difference is CreamDecorator over-ride parent class's makeCoffee() method to add cream instead of sugar*/
class CreamDecorator extends CoffeeDecorator
{
CreamDecorator(Coffee objCoffee) {
super(objCoffee);
}

public void makeCoffee() {
objDecoratedCoffee.makeCoffee();
addCream();
}

protected void addCream() {
// add cream procedure
}
}

/*Here is Milk Decorator...*/
class MilkDecorator extends CoffeeDecorator
{
MilkDecorator(Coffee objCoffee) {
super(objCoffee);
}

public void makeCoffee() {
addMilk();
objDecoratedCoffee.makeCoffee();
}

protected void addMilk()
{
// add milk to coffee
}
}

/*This is our Coffee Maker Class which deliver coffee on demand. Please look carefully how we create basic coffee and customize it according to demand*/

public class CoffeeMaker
{
public static void main( String []args) {
// Have Simple Coffee
Coffee objCoffee = new Coffee();
/* Need to add Sugar to Coffee*/
SugarDecorator sugaredCoffee = new SugarDecorator(objCoffee);
sugaredCoffee .makeCoffee();

/* Need to add cream to sugared coffee, just simple.. */
CreamDecorator creamCoffee =
new CreamDecorator(sugaredCoffee );
sugaredExtStrCoffee .majeCoffee();

/*Someone asked for coffee with cream and no sugar*/
CreamDecorator newOrder = new CreamDecorator(new Coffee());
newOrder.makeCoffee();
/*Forgot to add milk, no problem*/
MilkDecorator milkCoffee =
new MilkDecorator(newOrder);
milkCoffee.makeCoffee();
}
}
***********************************************************************
You must have noticed SugerDecorator constructor take Coffee type object hence any Coffee or sub class of coffee can be made with sugar using this single decorator. In other words, SugerDecorator doesn't care whether you are adding sugar to Simple Coffee or Creamed Coffee...it just add the sugar and returns your coffee...and so Cream Decorator does.
That's all, isn't this great. You don't need to make "N" subclasses to get sugared or creamed Coffee of any type but single decorator will do this for you
and your design remains pretty simple and flexible.
In the same way, you can create any type of decorator to add the new behavior irrespective of what kind of coffee your are passing to it, like ExtraHotDecorator...

So lets Summarize it,
Inheritance need 16 subclass to make 5 types of coffee and number of new subclasses increase in Arithmetic progression for any new functionality.
Decorator pattern need 1 base class and 5 Decorator i.e. total 6 classes to have same result and number of classes increase by 1 only for any new functionality
That's all about Decorator pattern. I hope you must have gotten a solid idea about Decorator pattern and how you can use in You Application Design. For any clarification, Please feel free to email me at mohit.amour@gmail.com

Thanks,
The Interpreter

Singleton Pattern - One For All Object

Singleton pattern is one of very basic and most widely used design pattern. You might have used Singleton pattern without knowing about it. If you are aware of struts framework, Action class (infact Child of Action Class) is Singleton. Action class is made singleton by Struts framework itself without your intervention but in your application design, you need to make sure which class is need to be Singleton.
Singleton pattern ensure there is one and only one instance (Object) of a Class exist at a time, in other words when you want only one object to be exist of some class, make is Singleton.

How to Implement Singleton Pattern,
Singleton pattern can be implemented in numerous ways but there are three standard way to implement singleton pattern.

1. Synchronized Method:
******************************************************************
Class MyClass
{
private static MyClass objSingleton = null;

/* to make sure class can’t be instantiated outside */
private MyClass()

/*this method returns singleton object*/
public static synchronized MyClass getInstance()
{
If ( null == objSingleton ) {
objSingleton = new MyClass();
}
return objSingleton;
}
//… Other Member of Class
}
******************************************************************
That’s all. Doesn’t it look simple to make MyClass singleton! Well all you need to do is create a private static object to make is make its scope global within the class. Then you need to make its constructor private so it cannot be instantiated from outside. Finally make a public static method to return the single instance of the object. Don’t forget to make the method synchronized to make it thread safe.
This approach is simple but as we know, make a method synchronized is really expensive in multi-threaded environment, so if your singleton object is need to used very frequently by many objects, abstain from this approach and read further ?…

2. Early Instantiation:
******************************************************************
Class MyClass
{
private static MyClass objSingleton = new MyClass();
/* to make sure class can’t be instantiated outside */
private MyClass()
/*this method returns singleton object*/
public static MyClass getInstance()
{
return objSingleton;
}
//… Other Member of Class
}
******************************************************************
This approach is most simple. You need to instantiate the object when you declared it, and forget everything except returning object from a static method. This approach is not encouraged much as it instantiate object before it is actually accessed but this will improve your access time to singleton object.

3. Double Lock Checking:
This will introduce some extra lines in your code but this is considered as best approach and endorsed in many case studies to implement singleton.
******************************************************************
Class MyClass
{
private volatile static MyClass objSingleton = null;
/* to make sure class can’t be instantiated outside */
private MyClass()
/*this method returns singleton object*/
public static MyClass getInstance()
{
If (null == objSingleton ) {
synchronized (MyClass.class) {
If (null == objSingleton ) {
objSingleton = new MyClass();
}
}
}
return objSingleton;
}
//… Other Member of Class
}
******************************************************************
This looks cumbersome but if you see, this is almost same as approach 1, except we are synchronizing over Class rather than Method. This reduced the synchronized codes hence improve the performance.

When to use singleton pattern:
Well this is not simple answer. This depends on your application design and your experience. You need to identify which all classes need to be singleton. A simple measure is, all class used as controller or handler class need to be singleton.
Few common scenarios are,
  • Data Source handling class
  • Property file handling class
  • Email handling class
  • Application Configuration class
Clone methos v/s Singleton pattern
When writing a class using the Singleton pattern, only one instance of that class can exist at a time. As a result, the class must not be allowed to make a clone. To prevent this, override the clone() method using the following code:

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();

}

Please make sure you are using above implementation of clone method only if you have implemented Clone interface in your singleton class as there is no need to place redundant method in your class....

We will continue discussing design pattern in coming posts,
In case of any query, feel free to email me at mohit.amour@gmail.com

Thank You,
The Interpreter


Factory Method Pattern - Choose Your Object

Factory method pattern is another powerful design pattern, which not only reduces the complexity of your application but make your design more flexible also.
The definition of factory stats: "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses."

Well this sounds little confusing, I understand that so we will explain this little better in our codes. For time being, just remember following,
  • We have a base abstract class
  • A Factory class can create and returns any child of that abstract class
Lets Walk through an example:
You like Pizza, well most of us do...we go to Dominos (or Pizza Hut, we are not advertising them) and order pizza based on catalog. We never bother about how they are creating different type of Pizzas. We order them and based on our order they made Pizza and return to us...Well, Thats all about Factory pattern. Isn't it simple. Dominos is our Pizza factory and they are returns us a subclass(like margarita, Farm Fresh, MushroomDelight...Yummy) of type Pizza (abstract class).
***********************************************************************
--------------------Creating Base Class Type------------------------------------
abstract class Pizza {
int getPrice();
}
--------------------Creating Actual Class/Product------------------
/* Margarita Pizza recipes*/
class MargaritaPizza extends Pizza {
public int getPrice() {
return 850;
}
}

/* Farm Fresh Pizza recipes*/
class FarmFreshPizza extends Pizza {
public int getPrice() {
return 1050;
}
}


/* Mushroom Delight Pizza recipes*/
class MushroomDelightPizza extends Pizza {
public int getPrice() {
return 1150;
}
}
------------------Creating Factory------------------------------
/*This is actual Pizza Factory*/
class PizzaFactory {
/*Create Pizza Type*/
public enum PizzaType {
Margarita,
FarmFresh,
MushroomDelight
}
/*create Pizza on orders*/
public static Pizza createPizza(PizzaType pizzaType) {
switch (pizzaType) {
case Margarita:
return new MargaritaPizza();
case FarmFresh:
return new FarmFreshPizza();
case MushroomDelight:
return new MushroomDelightPizza();
}
}
}
***********************************************************************
I guess codes are pretty simple and you must have gotten the real idea behind factory pattern. First you need to create a abstract class. then you need to extend that in your child class. Now all you need to do is create a Factory class which returns any of your child instance based on some type. You can use this Factory class to any where in your application to get Pizza according to your order type.
Here you can replace Pizza with any thing and your factory pattern for the scenario is implemented instantly.

When to use Factory Pattern,

  • A class cannot anticipate which kind of class of objects it must create.
  • A class uses its subclasses to specify which objects it creates.
  • You want to localize the knowledge of which class gets created.
There are several similar variations on the factory pattern to recognize.
  • The base class is abstract and the pattern must return a complete working class.
  • The base class contains default methods and is only subclassed for cases where the default methods are insufficient.
  • Parameters are passed to the factory telling it which of several class types to return. In this case the classes may share the same method names but may do something quite different
Thats all for Factory Pattern. Hope you enjoyed the Factory Pattern and built the concrete concept over it. We will continue with next Design Patten in coming posts.
In case of any query regarding this, Please feel free to email me at mohit.amour@gmail.com


Thanks.
The Interpreter