Monday, June 18, 2012

Abstract Factory Pattern

Introduction


Abstract Factory Pattern can be defined as factory of factories. You can see the reason by looking at the example.

Example


Suppose you have 2 factories. Each factory makes phones and laptops. Suppose first factory is AppleFactory and other one is ToshibaFactory. AppleFactory makes IPhone and Mac laptop. ToshibaFactory makes ToshibaPhone and ToshibaLaptop. Let's see the code.

Phone.java


package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public abstract class Phone {

 public abstract String getCategory();
 
}

Laptop.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public abstract class Laptop {

 public abstract String getOperatingSystem();
 
}

Factory.java


package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public interface Factory {

 public Phone createPhone();
 public Laptop createLaptop();
 
}

IPhone.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class IPhone extends Phone {

 @Override
 public String getCategory() {
  return "Mobile Phone";
 }
 
}

Mac.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class Mac extends Laptop {

 @Override
 public String getOperatingSystem() {
  return "Mac";
 }

}

AppleFactory.java

package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class AppleFactory implements Factory {

 @Override
 public Phone createPhone() {
  return new IPhone();
 }

 @Override
 public Laptop createLaptop() {
  return new Mac();
 }

}

ToshibaPhone.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class ToshibaPhone extends Phone {

 @Override
 public String getCategory() {
  return "Land Phone";
 }
 
}

ToshibaLaptop.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class ToshibaLaptop extends Laptop {

 @Override
 public String getOperatingSystem() {
  return "Windows 7";
 }

}

ToshibaFactory.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class ToshibaFactory implements Factory {

 @Override
 public Phone createPhone() {
  return new ToshibaPhone();
 }

 @Override
 public Laptop createLaptop() {
  return new ToshibaLaptop();
 }

}

Main.java



package com.blog.patterns.abstractfactory;

/**
 * @author uditha
 */
public class Main {

 public static void main(String[] args) {
  // apple factory
  Factory factory = new AppleFactory();
  Phone phone = factory.createPhone();
  Laptop laptop = factory.createLaptop();
  System.out.println(phone.getCategory());
  System.out.println(laptop.getOperatingSystem());
  
  // toshiba factory
  factory = new ToshibaFactory();
  phone = factory.createPhone();
  laptop = factory.createLaptop();
  System.out.println(phone.getCategory());
  System.out.println(laptop.getOperatingSystem());
 }

}

No comments:

Post a Comment