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

Uma lanchonete deseja implementar um sistema onde o usuário pode personalizar o seu cachorro-quente, inserindo adicionais ao produto base, como milho, queijo, cebola e assim por diante.

Os cachorros-quentes comercializados pela lanchonete são:

Tradicional (pão, molho de tomate e salsicha tradicional)     R$ 6,00
Especial (pão, molho de tomate e salsicha especial) R$ 7,00
Frango (pão, molho de tomate e salsicha de frango) R$ 7,80
Calabresa (pão, molho de tomate e salsicha calabresa) R$ 7,80

Os acompanhamentos que podem ser adicionados a qualquer um dos cachorros-quentes comercializados pela lanchonete são:

Cebola      R$ 0,30
Milho R$ 0,50
Ervilha R$ 0,50
Queijo R$ 0,70
Bacon R$ 0,70

Por exemplo, caso o cliente selecione o tradicional + milho + queijo + bacon o sistema deverá informar ao cliente na nota fiscal:

Tradicional (pão, molho de tomate e salsicha tradicional)     R$ 6,00
Milho R$ 0,50
Queijo R$ 0,70
Bacon R$ 0,70
TOTAL R$ 7,90

Desenvolva o sistema solicitado, utilizando o padrão de projeto Decorator.

 

Diagrama de Classes na Linguagem de Programação Java Produto.java Calabresa.java Especial.java Frango.java Tradicional.java Acompanhamento.java Bacon.java Cebola.java Ervilha.java Milho.java Queijo.java Total.java Application.java
Diagrama de Classes
Diagrama de Classes na Linguagem de Programação Java

Arquivo Produto.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.tutorial09.exercicio28;

import java.text.NumberFormat;
import java.util.Locale;

/**
 * Representação dos produtos comercializados pela lanchonete
 *
 * Component - define a interface para objetos que podem ter
 * responsabilidades acrescentadas aos mesmos dinamicamente (Gamma, 2000)
 */
public abstract class Produto
{
  /**
   * Tamanho máximo da apresentação do produto
   */
  public static final int SIZE = 60;

  /**
   * Descrição do produto
   */
  private String descricao;

  /**
   * Nome do produto
   */
  private String nome;

  /**
   * Preço do produto
   */
  private double preco;

  /**
   * Retornar o produto no cupon fiscal
   *
   * @return produto no cupon fiscal
   */
  protected String getCupom()
  {
    return toString();
  }

  /**
   * Retornar a descrição do produto
   *
   * @return descrição do produto
   */
  public String getDescricao()
  {
    return descricao;
  }

  /**
   * Retornar o nome do produto
   *
   * @return nome do produto
   */
  public String getNome()
  {
    return nome;
  }

  /**
   * Retornar o preço do produto
   *
   * @return preço do produto
   */
  public double getPreco()
  {
    return preco;
  }

  /**
   * Retornar o preço total do cupom
   *
   * @return preço total do cupom
   */
  protected double getTotal()
  {
    return preco;
  }

  /**
   * Retornar o texto formatado do produto para impressão
   *
   * @param produto nome e descrição do produto, se for o caso
   * @param valor valor do produto
   * @return texto formatado do produto para impressão
   */
  protected String printProduto(String produto, double valor)
  {
    StringBuilder buffer = new StringBuilder();

    if(produto.length() < SIZE)
    {
      buffer.append(produto);

      for(int size = produto.length(); size < SIZE; size++)
      {
        buffer.append(" ");
      }
    }
    else
    {
      buffer.append(produto.substring(0, SIZE));
    }

    Locale brazil = new Locale("pt", "BR");

    NumberFormat numberFormat =  NumberFormat.getCurrencyInstance(brazil);

    buffer.append("  ")
          .append(numberFormat.format(valor))
          .append("\n");

    return buffer.toString();
  }

  /**
   * Configurar a descrição do produto
   *
   * @param descricao descrição do produto
   */
  protected void setDescricao(String descricao)
  {
    this.descricao = descricao;
  }

  /**
   * Configurar o nome do produto
   *
   * @param nome nome do produto
   */
  protected void setNome(String nome)
  {
    this.nome = nome;
  }

  /**
   * Configurar o preço do produto
   *
   * @param preco preço do produto
   */
  protected void setPreco(double preco)
  {
    this.preco = preco;
  }

  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString()
  {
    String produto = nome;

    if(descricao != null)
    {
      produto = produto + " (" + descricao + ")";
    }

    return printProduto(produto, preco);
  }
}

Arquivo Calabresa.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.tutorial09.exercicio28;

/**
 * Representação do cachorro-quente de calabresa
 *
 * ConcreteComponent - define um objeto para o qual responsabilidades
 * adicionais podem ser atribuídas (Gamma, 2000)
 */
public class Calabresa extends Produto
{
  /**
   * Inicializar o cachorro-quente de calabresa
   */
  public Calabresa()
  {
    setNome("Calabresa");

    setDescricao("pão, molho de tomate e salsicha de calabresa");

    setPreco(7.8);
  }
}

Arquivo Especial.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.tutorial09.exercicio28;

/**
 * Representação do cachorro-quente especial
 *
 * ConcreteComponent - define um objeto para o qual responsabilidades
 * adicionais podem ser atribuídas (Gamma, 2000)
 */
public class Especial extends Produto
{
  /**
   * Inicializar o cachorro-quente especial
   */
  public Especial()
  {
    setNome("Especial");

    setDescricao("pão, molho de tomate e salsicha especial");

    setPreco(7.0);
  }
}

Arquivo Frango.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.tutorial09.exercicio28;

/**
 * Representação do cachorro-quente de frango
 *
 * ConcreteComponent - define um objeto para o qual responsabilidades
 * adicionais podem ser atribuídas (Gamma, 2000)
 */
public class Frango extends Produto
{
  /**
   * Inicializar o cachorro-quente de frango
   */
  public Frango()
  {
    setNome("Frango");

    setDescricao("pão, molho de tomate e salsicha de frango");

    setPreco(7.8);
  }
}

Arquivo Tradicional.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.tutorial09.exercicio28;

/**
 * Representação do cachorro-quente tradicional
 *
 * ConcreteComponent - define um objeto para o qual responsabilidades
 * adicionais podem ser atribuídas (Gamma, 2000)
 */
public class Tradicional extends Produto
{
  /**
   * Inicializar o cachorro-quente tradicional
   */
  public Tradicional()
  {
    setNome("Tradicional");

    setDescricao("pão, molho de tomate e salsicha tradicional");

    setPreco(6.0);
  }
}

Arquivo Acompanhamento.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.tutorial09.exercicio28;

/**
 * Representação dos acompanhamentos comercializados pela lanchonete
 *
 * Decorator - mantém uma referência para um objeto Component e define
 * uma interface que segue a interface de Component (Gamma, 2000)
 */
public abstract class Acompanhamento extends Produto
{
  /**
   * Produto comercializado pela lanchonete
   */
  protected Produto produto;

  /**
   * Inicializar o acompanhamento
   *
   * @param produto produto comercializado pela lanchonete
   */
  public Acompanhamento(Produto produto)
  {
    this.produto = produto;
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial09.exercicio28.Produto#getCupom()
   */
  @Override
  protected String getCupom()
  {
    return produto.getCupom() + toString();
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial09.exercicio28.Produto#getTotal()
   */
  @Override
  protected double getTotal()
  {
    return produto.getTotal() + getPreco();
  }
}

Arquivo Bacon.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.tutorial09.exercicio28;

/**
 * Representação do acompanhamento bacon
 *
 * ConcreteDecorator - acrescenta responsabilidades ao componente
 * (Gamma, 2000)
 */
public class Bacon extends Acompanhamento
{
  /**
   * Inicializar o acompanhamento bacon
   *
   * @param produto produto comercializado pela lanchonete
   */
  public Bacon(Produto produto)
  {
    super(produto);

    setNome("Bacon");

    setPreco(0.7);
  }
}

Arquivo Cebola.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.tutorial09.exercicio28;

/**
 * Representação do acompanhamento cebola
 *
 * ConcreteDecorator - acrescenta responsabilidades ao componente
 * (Gamma, 2000)
 */
public class Cebola extends Acompanhamento
{
  /**
   * Inicializar o acompanhamento cebola
   *
   * @param produto produto comercializado pela lanchonete
   */
  public Cebola(Produto produto)
  {
    super(produto);

    setNome("Cebola");

    setPreco(0.3);
  }
}

Arquivo Ervilha.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.tutorial09.exercicio28;

/**
 * Representação do acompanhamento ervilha
 *
 * ConcreteDecorator - acrescenta responsabilidades ao componente
 * (Gamma, 2000)
 */
public class Ervilha extends Acompanhamento
{
  /**
   * Inicializar o acompanhamento ervilha
   *
   * @param produto produto comercializado pela lanchonete
   */
  public Ervilha(Produto produto)
  {
    super(produto);

    setNome("Ervilha");

    setPreco(0.5);
  }
}

Arquivo Milho.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.tutorial09.exercicio28;

/**
 * Representação do acompanhamento milho
 *
 * ConcreteDecorator - acrescenta responsabilidades ao componente
 * (Gamma, 2000)
 */
public class Milho extends Acompanhamento
{
  /**
   * Inicializar o acompanhamento milho
   *
   * @param produto produto comercializado pela lanchonete
   */
  public Milho(Produto produto)
  {
    super(produto);

    setNome("Milho");

    setPreco(0.5);
  }
}

Arquivo Queijo.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.tutorial09.exercicio28;

/**
 * Representação do acompanhamento queijo
 *
 * ConcreteDecorator - acrescenta responsabilidades ao componente
 * (Gamma, 2000)
 */
public class Queijo extends Acompanhamento
{
  /**
   * Inicializar o acompanhamento queijo
   *
   * @param produto produto comercializado pela lanchonete
   */
  public Queijo(Produto produto)
  {
    super(produto);

    setNome("Queijo");

    setPreco(0.7);
  }
}

Arquivo Total.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.tutorial09.exercicio28;

/**
 * Representação do total do cupom fiscal
 *
 * ConcreteDecorator - acrescenta responsabilidades ao componente
 * (Gamma, 2000)
 */
public class Total extends Acompanhamento
{
  /**
   * Inicializar o total do cumpom fiscal
   *
   * @param produto produto comercializado pela lanchonete
   */
  public Total(Produto produto)
  {
    super(produto);

    setNome("TOTAL");
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial09.exercicio28.Produto#getCupom()
   */
  @Override
  protected String getCupom()
  {
    return produto.getCupom() + printProduto(getNome(), getTotal());
  }
}

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.tutorial09.exercicio28;

/**
 * Classe responsável pela execução do padrão de projeto Decorator
 */
public class Application
{
  /**
   * Construtor para inicializar a execução do padrão de projeto Decorator
   */
  private Application()
  {

  }

  /**
   * Método principal da linguagem de programação Java
   *
   * @param args argumentos da linha de comando (não utilizado)
   */
  public static void main(String[] args)
  {
    Produto pedido = new Total(new Queijo(new Milho(new Tradicional())));

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