easy, elegant and effective code…

Given below is the sample java implementation of the “Abstract Factory” design pattern where we are instantiating the object of widgets (window/button) of a required family (motif or mac).
We need to select a factory of specific family once only …then we automatically get all the objects of the specified family; we need not specify the family every time …we want to instantiate an object.

interface XWindow
{ 
}

class MotifWindow implements XWindow
{
   public MotifWindow()
   {
      System.out.println("MotifWindow Created.");
   }
}

class MacWindow implements XWindow
{
   public MacWindow()
   {
      System.out.println("MacWindow Created.");
   }
}

interface XButton
{
   
}

class MotifButton implements XButton
{
   public MotifButton()
   {
      System.out.println("MotifButton Created.");
   }
}

class MacButton implements XButton
{
   public MacButton()
   {
      System.out.println("MacButton Created.");
   }
}

interface WidgetFacotry
{
   XWindow createXWindow();
   XButton createXButton();
}

class MotifWidgetFactory implements WidgetFacotry
{

   @Override
   public XButton createXButton()
   {
      return new MotifButton();
   }

   @Override
   public XWindow createXWindow()
   {
      return new MotifWindow();
   }
  
}

class MacWidgetFactory implements WidgetFacotry
{

   @Override
   public XButton createXButton()
   {
      return new MacButton();
   }

   @Override
   public XWindow createXWindow()
   {
      return new MacWindow();
   }   
}

public class AbstractFactory
{
   public static void main(String args[])
   {
      WidgetFacotry factory = new MacWidgetFactory();
      //WidgetFacotry factory = new MotifWidgetFactory();
      
      factory.createXWindow();
      factory.createXButton();      
   }   
}

On executing the above program, you are going to get the following output –

MacWindow Created.
MacButton Created.

If you comment the line #85 and un-comment the line #86, you will get the following output –

MotifWindow Created.
MotifButton Created.
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: