Java Design Patterns Abstract Factory Patterns

Introduction

Abstract Factory Patterns provides an interface for creating families of objects without specifying their concrete classes.

Example

interface Client//ww  w  .  j  av a2 s.c o  m
{
  String getLangName();
}

interface Server
{
  String getLangName();
}

interface LanguageFactory
{
  Client getClient();
  Server getServer();
}

class StyleLang implements Client
{
  @Override
  public String getLangName() 
  { 
    return "CSS";  
  }
}

class MarkupLang implements Client
{
  @Override
  public String getLangName() 
  { 
    return "HTML";
  } 
}
class MiddleLayerLang implements Server
{
  @Override 
  public String getLangName() 
  {
    return "Java";
  }
}

class LowLevelLang implements Server
{
  @Override 
  public String getLangName() 
  {
    return "C++";  
  }
}
class BusinessAppFactory implements LanguageFactory
{
  public Client getClient()
  {
    return new StyleLang();
  }

  public Server getServer()
  {
    return new MiddleLayerLang();
  }
}

class GameAppFactory implements LanguageFactory
{
  public Client getClient()
  {
    return new MarkupLang();
  }

  public Server getServer()
  {
    return new LowLevelLang();
  }
}
public class Main 
{
  public static void main(String[] args)
  {
    BusinessAppFactory businessApp = new BusinessAppFactory();
    Client tAction = businessApp.getClient();
    Server bAction = businessApp.getServer();

    System.out.println("\nAction movies  are:");             
    System.out.println(tAction.getLangName());
    System.out.println(bAction.getLangName());


    GameAppFactory gameApp = new GameAppFactory();
    Client tComedy = gameApp.getClient();
    Server bComedy = gameApp.getServer();

    System.out.println("\nComedy movies  are:");
    System.out.println(tComedy.getLangName());
    System.out.println(bComedy.getLangName());        
  }
}



PreviousNext

Related