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

Desenvolva um programa que exporte os valores armazenados numa matriz de inteiros nos formatos CSV, XML ou JSON, utilizando como base o padrão de projeto Visitor.

Por exemplo, considere que os valores armazenados na matriz sejam:

0 1 2 3
4 5 6 7
8 9 8 7

Caso os valores sejam exportados no formato CSV, a saída deverá ser

0;1;2;3
4;5;6;7
8;9;8;7

Caso os valores sejam exportados no formato XML, a saída deverá ser

<table>
  <row>
    <column>0</column>
    <column>1</column>
    <column>2</column>
    <column>3</column>
  </row>
  <row>
    <column>4</column>
    <column>5</column>
    <column>6</column>
    <column>7</column>
  </row>
  <row>
    <column>8</column>
    <column>9</column>
    <column>8</column>
    <column>7</column>
  </row>
</table>

Caso os valores sejam exportados no formato JSON, a saída deverá ser

{"table":[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 8, 7]]}

 

Diagrama de Classes na Linguagem de Programação Java Matrix.java IntegerMatrix.java Exporter.java CsvExporter.java JsonExporter.java XmlExporter.java Application.java
Diagrama de Classes
Diagrama de Classes na Linguagem de Programação Java

Arquivo Matrix.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.tutorial10.exercicio37;

/**
 * Especificação da matriz
 *
 * Element - define uma operação accept que aceita um visitante como um
 *   argumento (Gamma, 2000)
 */
public interface Matrix
{
  /**
   * Processar a exportação por meio do exportador especificado
   *
   * @param exporter exportador
   * @return matriz exportada
   */
  public String accept(Exporter exporter);
}

Arquivo IntegerMatrix.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.tutorial10.exercicio37;

/**
 * Implementação de uma matriz de inteiros
 *
 * ConcreteElement - implementa uma operação accept que aceita um visitante
 *   como um argumento (Gamma, 2000)
 */
public class IntegerMatrix implements Matrix
{
  /**
   * Matriz de inteiros
   */
  private Integer[][] matrix;

  /**
   * Inicializar a matriz de inteiros
   *
   * @param matrix matriz de inteiros
   */
  public IntegerMatrix(Integer[][] matrix)
  {
    this.matrix = matrix;
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial10.exercicio37.Matrix#
   *   accept(com.ybadoo.tutoriais.poo.tutorial10.exercicio37.Exporter)
   */
  @Override
  public String accept(Exporter exporter)
  {
    return exporter.visit(this);
  }

  /**
   * Retornar o elemento armazenado na linha e columa especificado
   *
   * @param row linha
   * @param column coluna
   * @return elemento armazenado na linha e columa especificado
   */
  public Integer get(int row, int column)
  {
    return matrix[row][column];
  }

  /**
   * Retornar o número de colunas da linha especificada
   *
   * @param row linha
   * @return número de colunas da linha especificada
   */
  public int getColumns(int row)
  {
    return matrix[row].length;
  }

  /**
   * Retornar o número de linhas da matriz de inteiros
   *
   * @return número de linhas da matriz de inteiros
   */
  public int getRows()
  {
    return matrix.length;
  }
}

Arquivo Exporter.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.tutorial10.exercicio37;

/**
 * Especificação dos exportadores
 *
 * Visitor - declara uma operação visit para cada classe ConcreteElement na
 *   estrutura do objeto. O nome e a assinatura da operação identifica a
 *   classe que envia a solicitação visit ao visitante. Isto permite ao
 *   visitante determinar a classe concreta do elemento que está sendo
 *   visitado. Então, o visitante pode acessar o elemento diretamente
 *   através da sua interface específica (Gamma, 2000)
 */
public interface Exporter
{
  /**
   * Visitar o elemento especificado
   *
   * @param element elemento especificado
   * @return elemento exportado
   */
  public String visit(IntegerMatrix element);
}

Arquivo CsvExporter.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.tutorial10.exercicio37;

/**
 * Exportador dos valores em CSV
 *
 * ConcreteVisitor - implementa cada operação declarada por Visitor. Cada
 *   operação implementa um fragmento do algoritmo definido para a
 *   correspondente classe de objeto na estrutura. ConcreteVisistor fornece
 *   o contexto para o algoritmo e armazena o seu estado local. Este estado,
 *   frequentemente, acumula resultados durante o percurso da estrutura
 *   (Gamma, 2000)
 */
public class CsvExporter implements Exporter
{
  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial10.exercicio37.Exporter#
   *   visit(com.ybadoo.tutoriais.poo.tutorial10.exercicio37.IntegerMatrix)
   */
  @Override
  public String visit(IntegerMatrix element)
  {
    StringBuilder out = new StringBuilder();

    for (int row = 0; row < element.getRows(); row++)
    {
      boolean first = true;

      for (int column = 0; column < element.getColumns(row); column++)
      {
        if (first)
        {
          first = false;
        }
        else
        {
          out.append(';');
        }

        out.append(element.get(row, column));
      }

      out.append('\n');
    }

    return out.toString();
  }
}

Arquivo JsonExporter.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.tutorial10.exercicio37;

/**
 * Exportador dos valores em JSON
 *
 * ConcreteVisitor - implementa cada operação declarada por Visitor. Cada
 *   operação implementa um fragmento do algoritmo definido para a
 *   correspondente classe de objeto na estrutura. ConcreteVisistor fornece
 *   o contexto para o algoritmo e armazena o seu estado local. Este estado,
 *   frequentemente, acumula resultados durante o percurso da estrutura
 *   (Gamma, 2000)
 */
public class JsonExporter implements Exporter
{
  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial10.exercicio37.Exporter#
   *   visit(com.ybadoo.tutoriais.poo.tutorial10.exercicio37.IntegerMatrix)
   */
  @Override
  public String visit(IntegerMatrix element)
  {
    StringBuilder out = new StringBuilder();

    out.append("{\"table\":[");

    boolean firstRow = true;

    for (int row = 0; row < element.getRows(); row++)
    {
      boolean firstColumn = true;

      if (firstRow)
      {
        out.append('[');

        firstRow = false;
      }
      else
      {
        out.append(", [");
      }

      for (int column = 0; column < element.getColumns(row); column++)
      {
        if (firstColumn)
        {
          firstColumn = false;
        }
        else
        {
          out.append(", ");
        }

        out.append(element.get(row, column));
      }

      out.append(']');
    }

    out.append("]}");

    return out.toString();
  }
}

Arquivo XmlExporter.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.tutorial10.exercicio37;

/**
 * Exportador dos valores em XML
 *
 * ConcreteVisitor - implementa cada operação declarada por Visitor. Cada
 *   operação implementa um fragmento do algoritmo definido para a
 *   correspondente classe de objeto na estrutura. ConcreteVisistor fornece
 *   o contexto para o algoritmo e armazena o seu estado local. Este estado,
 *   frequentemente, acumula resultados durante o percurso da estrutura
 *   (Gamma, 2000)
 */
public class XmlExporter implements Exporter
{
  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial10.exercicio37.Exporter#
   *   visit(com.ybadoo.tutoriais.poo.tutorial10.exercicio37.IntegerMatrix)
   */
  @Override
  public String visit(IntegerMatrix element)
  {
    StringBuilder out = new StringBuilder();

    out.append("<table>\n");

    for (int row = 0; row < element.getRows(); row++)
    {
      out.append("  <row>\n");

      for (int column = 0; column < element.getColumns(row); column++)
      {
        out.append("    <column>")
           .append(element.get(row, column))
           .append("</column>\n");
      }

      out.append("  </row>\n");
    }

    out.append("</table>");

    return out.toString();
  }
}

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.tutorial10.exercicio37;

/**
 * Classe responsável pela execução do padrão Visitor
 */
public class Application
{
  /**
   * Construtor para inicializar a execução do padrão Visitor
   */
  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)
  {
    Integer[][] matrix = {{0, 1, 2, 3}, {4, 5, 6, 7}, {8, 9, 8, 7}};

    IntegerMatrix integerMatrix = new IntegerMatrix(matrix);

    CsvExporter csvExporter = new CsvExporter();

    System.out.println(csvExporter.visit(integerMatrix));

    XmlExporter xmlExporter = new XmlExporter();

    System.out.println(xmlExporter.visit(integerMatrix));

    JsonExporter jsonExporter = new JsonExporter();

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