Friday, October 19, 2012

Creational Design Pattern : Abstract Factory


Abstract Factory is a creational design pattern and it provides one level of interface higher than the Factory design pattern.
Problem:
To create complex objects, we use the factory method but it provides same class object for that method.
Solution:
We provide one extra interface to switch the factory.
Implementation:
Button.java:
public interface Button {
      public void click();
}
Xbutton.java:
public class XButton implements Button {
      @Override
      public void click() {
            System.out.println("XButton is clicked.");
      }
}
Ybutton.java:
public class YButton implements Button {
      @Override
      public void click() {
            System.out.println("YButton is clicked.");
      }
}
ButtonFactory.java:
public interface ButtonFactory {
      public Button createButton();
}
XButtonFactory.java:
public class XButtonFactory implements ButtonFactory {
      @Override
      public Button createButton() {     
            return new XButton();
      }
}
YButtonFactory.java:
public class YButtonFactory implements ButtonFactory{
      @Override
      public Button createButton() {
            return new YButton();
      }
}
Test.java:
public class Test {
      public static void main(String[] args) {
        ButtonFactory factory = new XButtonFactory();
        Button button = factory.createButton();
        button.click();
        factory = new YButtonFactory();
        button = factory.createButton();
        button.click();
    }
}

No comments:

Post a Comment