Ybadoo - Soluções em Software Livre
Tutoriais
Programação Orientada a Objetos

Para exercitar a utilização do padrão de projeto Factory Method, desenvolva uma fábrica de motores, que construa motores de aço, de alumínio e elétricos.

O Product é um motor.

Os ConcreteProduct são os motores de aço, de alumínio e elétricos.

Os motores de alumínio podem ser de 3 ou 6 cilindros.

Os motores de aço podem ser de 4 ou 8 cilindros.

Os motores elétricos não possuem cilindros.

O Creator é o metalúrgico.

Os ConcreteCreator são os metalúrgicos alemão, brasileiro e japonês.

O metalúrgico alemão cria motores de alumínio.

O metalúrgico brasileiro cria motores de aço.

O metalúrgico japonês cria motores elétricos.

 

Diagrama de Classes na Linguagem de Programação Java Engine.java AluminumEngine.java SteelEngine.java ElectricEngine.java Metallurgist.java GermanMetallurgist.java BrazilianMetallurgist.java JapaneseMetallurgist.java Application.java
Diagrama de Classes
Diagrama de Classes na Linguagem de Programação Java

Arquivo Engine.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial08.exercicio11;

/**
 * Especificacao do motor
 *
 * Product define a interface de objetos que o metodo factory cria
 *         (Gamma, 2000).
 */
public interface Engine
{
  /**
   * Retornar o numero de cilindros do motor
   *
   * @return numero de cilindros do motor
   */
  public int cylinders();
}

Arquivo AluminumEngine.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial08.exercicio11;

/**
 * Especificacao do motor de aluminio
 *
 * ConcreteProduct implementa a interface de Product (Gamma, 2000).
 */
public class AluminumEngine implements Engine
{
  /**
   * Numero de cilindros do motor de aluminio
   */
  private int cylinders;

  /**
   * Inicializar o motor de aluminio
   *
   * @param cylinders numero de cilindros do motor de aluminio
   */
  public AluminumEngine(int cylinders)
  {
    if((cylinders == 3) || (cylinders == 6))
    {
      this.cylinders = cylinders;
    }
    else
    {
      throw new IllegalArgumentException("O número de cilindros do " + 
        "motor de alumínio deve ser 3 ou 6");
    }
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial08.exercicio11.Engine#cylinders()
   */
  @Override
  public int cylinders()
  {
    return cylinders;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString()
  {
    return "Motor de alumínio de " + cylinders + " cilindros";
  }
}

Arquivo SteelEngine.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial08.exercicio11;

/**
 * Especificacao do motor de aco
 *
 * ConcreteProduct implementa a interface de Product (Gamma, 2000).
 */
public class SteelEngine implements Engine
{
  /**
   * Numero de cilindros do motor de aco
   */
  private int cylinders;

  /**
   * Inicializar o motor de aco
   *
   * @param cylinders numero de cilindros do motor de aco
   */
  public SteelEngine(int cylinders)
  {
    if((cylinders == 4) || (cylinders == 8))
    {
      this.cylinders = cylinders;
    }
    else
    {
      throw new IllegalArgumentException("O número de cilindros do motor " +
        "de aço deve ser 4 ou 8");
    }
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial08.exercicio11.Engine#cylinders()
   */
  @Override
  public int cylinders()
  {
    return cylinders;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString()
  {
    return "Motor de aço de " + cylinders + " cilindros";
  }
}

Arquivo ElectricEngine.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial08.exercicio11;

/**
 * Especificacao do motor eletrico
 *
 * ConcreteProduct implementa a interface de Product (Gamma, 2000).
 */
public class ElectricEngine implements Engine
{
  /**
   * Inicializar o motor eletrico
   */
  public ElectricEngine()
  {
    // Nenhum atributo a ser inicializado
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial08.exercicio11.Engine#cylinders()
   */
  @Override
  public int cylinders()
  {
    return 0;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString()
  {
    return "Motor elétrico";
  }
}

Arquivo Metallurgist.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial08.exercicio11;

/**
 * Especificacao do metalurgico
 *
 * Creator declara o metodo factory o qual retorna um objeto do tipo
 *         Product. Creator pode tambem definir uma implementacao por
 *         omissao do metodo factory que retorna por omissao um objeto
 *         ConcreteProduct. Pode chamar o metodo factory para criar um
 *         objeto Product (Gamma, 2000).
 */
public abstract class Metallurgist
{
  /**
   * Construir o motor (metodo factory)
   *
   * @param cylinders numero de cilindros do motor
   * @return motor
   */
  protected abstract Engine buildEngine(int cylinders);

  /**
   * Retornar o motor especificado pelo usuario
   *
   * @param cylinders numero de cilindros do motor
   * @return motor especificado pelo usuario
   */
  public static Engine getEngine(int cylinders)
  {
    Metallurgist metallurgist = null;

    if(cylinders == 0)
    {
      metallurgist = new JapaneseMetallurgist();
    }
    else if((cylinders == 3) || (cylinders == 6))
    {
      metallurgist = new GermanMetallurgist();
    }
    else if((cylinders == 4) || (cylinders == 8))
    {
      metallurgist = new BrazilianMetallurgist();
    }
    else
    {
      throw new IllegalArgumentException("O número de cilindros do motor " +
        "é inválido");
    }

    return metallurgist.buildEngine(cylinders);
  }
}

Arquivo GermanMetallurgist.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial08.exercicio11;

/**
 * Metalurgico alemao
 *
 * ConcreteCreator redefine (overrides) o metodo factory para retornar
 *                 uma instancia de um ConcreteProduct (Gamma, 2000).
 */
public class GermanMetallurgist extends Metallurgist
{
  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial08.exercicio11.Metallurgist#buildEngine(int)
   */
  @Override
  protected Engine buildEngine(int cylinders)
  {
    return new AluminumEngine(cylinders);
  }
}

Arquivo BrazilianMetallurgist.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial08.exercicio11;

/**
 * Metalurgico brasileiro
 *
 * ConcreteCreator redefine (overrides) o metodo factory para retornar
 *                 uma instancia de um ConcreteProduct (Gamma, 2000).
 */
public class BrazilianMetallurgist extends Metallurgist
{
  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial08.exercicio11.Metallurgist#buildEngine(int)
   */
  @Override
  protected Engine buildEngine(int cylinders)
  {
    return new SteelEngine(cylinders);
  }
}

Arquivo JapaneseMetallurgist.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial08.exercicio11;

/**
 * Metalurgico japones
 *
 * ConcreteCreator redefine (overrides) o metodo factory para retornar
 *                 uma instancia de um ConcreteProduct (Gamma, 2000).
 */
public class JapaneseMetallurgist extends Metallurgist
{
  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial08.exercicio11.Metallurgist#buildEngine(int)
   */
  @Override
  protected Engine buildEngine(int cylinders)
  {
    return new ElectricEngine();
  }
}

Arquivo Application.java

/*************************************************************************
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)  *
 *                  Ybadoo - Solucoes em Software Livre (ybadoo.com.br)  *
 *                                                                       *
 * Permission is granted to copy, distribute and/or modify this document *
 * under the terms of the GNU Free Documentation License, Version 1.3 or *
 * any later version published by the  Free Software Foundation; with no *
 * Invariant Sections,  no Front-Cover Texts, and no Back-Cover Texts. A *
 * A copy of the  license is included in  the section entitled "GNU Free *
 * Documentation License".                                               *
 *                                                                       *
 * Ubuntu 16.10 (GNU/Linux 4.8.0-39-generic)                             *
 * OpenJDK Version "1.8.0_121"                                           *
 * OpenJDK 64-Bit Server VM (build 25.121-b13, mixed mode)               *
 *************************************************************************/

package com.ybadoo.tutoriais.poo.tutorial08.exercicio11;

/**
 * Classe responsavel pela execucao do padrao Factory Method
 */
public class Application
{
  /**
   * Construtor para inicializar a execucao do padrao Factory Method
   */
  private Application()
  {

  }

  /**
   * Metodo principal da linguagem de programacao Java
   *
   * @param args argumentos da linha de comando (nao utilizado)
   */
  public static void main(String[] args)
  {
    Engine electricEngine = Metallurgist.getEngine(0);

    System.out.println(electricEngine);

    Engine aluminumEngine = Metallurgist.getEngine(3);

    System.out.println(aluminumEngine);

    Engine steelEngine = Metallurgist.getEngine(4);

    System.out.println(steelEngine);
  }
}

Gamma, Erich. (2000). Padrões de Projeto: soluções reutilizáveis de software orientado a objetos. Porto Alegre: Bookman. 364 páginas.