Read more : http://www.ehow.com/how_8498918_remove-title-blogger-pages.html

Friday, 1 August 2014

Abstract Factory Design Pattern Example in Java

Hi,

"Abstarct factory " design pattern is used to creating objects of same type(family of same/related objects), without exposing their actual classes to the client or without specifying their classes explicitly.
Here we are mainly concentrating on creating the objects of family of  same type, and hence  this concept comes under creational pattern.

Please refer the below example for better understanding.


I have a factory interface  as follows

public interface FactoryInterface {
void sayHi();
void sayBye();
}

Below two classes implements factory interface

Women Implementation and
public class WomenImplementation implements FactoryInterface{

@Override
public void sayBye() {
System.out.println("Women saying Bye");
}

@Override
public void sayHi() {
System.out.println("Women saying Hi");
}

}

Men Implementation
public class MenImplementation implements FactoryInterface {

@Override
public void sayBye() {
System.out.println("Men saying Bye");
}

@Override
public void sayHi() {
System.out.println("Men Saying Hi");
}

}

If you observe women and men implemenations are belongs to same group or family of type FactoryInterface.

I have a factory controller which actually creates the objects of the classes.

public class FactoryController {
private static FactoryInterface factoryInterface=null;
public static FactoryInterface getInstance(String choice){
if(choice.equalsIgnoreCase("men")){
factoryInterface=new MenImplementation();
}else if(choice.equalsIgnoreCase("women")){
factoryInterface=new WomenImplementation();
}
return factoryInterface;
}

}

And my client class as follows

public class ClientFactory {
public static void main(String[] args) {
FactoryInterface fact1=FactoryController.getInstance("Men");
fact1.sayHi();
fact1.sayBye();
}
}

If you observe , client actually calling controller class by specifieng type of object he wants to create, he is not creating the object of the class, controller will takes care of creating the object of the class based on the client input , and we are completely hiding the data to the client, and only controller is visible to the client.

Please refer the class diagram for the above example.

No comments:

Post a Comment