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

Desenvolva um programa que realize a iteração sobre os elementos de uma matriz, utilizando o padrão de projeto Iterator.

 

Diagrama de Classes na Linguagem de Programação Java Iterator.java Container.java Matrix.java Application.java
Diagrama de Classes
Diagrama de Classes na Linguagem de Programação Java

Arquivo Iterator.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.exercicio32;

import java.util.NoSuchElementException;

/**
 * Interface com os metodos de navegacao pela iteracao
 *
 * Iterator define uma interface para acessar e percorrer elementos
 * (Gamma, 2000)
 *
 * @param <T> tipo de elemento retornado por esse iterador
 */
public interface Iterator<T>
{
  /**
   * Retornar true se a iteracao tem mais elementos
   *
   * @return true se a iteracao tem mais elementos
   */
  public boolean hasNext();

  /**
   * Retornar o proximo elemento na iteracao
   *
   * @return proximo elemento na iteracao
   * @throws NoSuchElementException se a iteracao nao tem mais elementos
   */
  public T next();
}

Arquivo Container.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.exercicio32;

/**
 * Interface para retornar um iterador
 *
 * Aggregate define uma interface para a criacao de um objeto
 * Iterator (Gamma, 2000)
 *
 * @param <T> tipo de elemento manuseado pelo iterador
 */
public interface Container<T>
{
  /**
   * Retornar o iterador do conjunto de elementos
   *
   * @return iterador do conjunto de elementos
   */
  public Iterator<T> getIterator();
}

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.exercicio32;

import java.util.NoSuchElementException;

/**
 * Representacao de uma matriz de elementos
 *
 * ConcreteAggregate implementa a interface de criacao do
 * Iterator para retornar uma instancia do ConcreteIterator
 * apropriado (Gamma, 2000)
 *
 * @param <T> tipo de elemento armazenado na matriz
 */
public class Matrix<T> implements Container<T>
{
  /**
   * Iterador para uma matriz de elementos
   *
   * ConcreteIterator implementa a interface de Iterator e mantem
   * o controle da posicao corrente no percurso do agregado
   * (Gamma, 2000)
   *
   * @param <T> tipo de elemento retornado por esse iterador
   */
  private class MatrixIterator implements Iterator<T>
  {
    /**
     * Linha atual da matriz
     */
    private int line;

    /**
     * Coluna atual da matriz
     */
    private int column;

    /**
     * Inicializar o iterador
     */
    public MatrixIterator()
    {
      line = 0;

      column = 0;
    }

    /* (non-Javadoc)
     * @see com.ybadoo.tutoriais.poo.tutorial10.exercicio32.
     *      Iterator#hasNext()
     */
    @Override
    public boolean hasNext()
    {
      return line < values.length;
    }

    /* (non-Javadoc)
     * @see com.ybadoo.tutoriais.poo.tutorial10.exercicio32.
     *      Iterator#next()
     */
    @Override
    public T next()
    {
      T temp;

      try
      {
        temp = values[line][column];
      }
      catch(IndexOutOfBoundsException exception)
      {
        throw new NoSuchElementException(exception.getMessage());
      }

      column = column + 1;

      if(column >= values[line].length)
      {
        column = 0;

        line = line + 1;
      }

      return temp;
    }
  }

  /**
   * Valores armazenados na matriz
   */
  private T[][] values;

  /**
   * Construtor para inicializar a matriz
   *
   * @param values valores armazenados na matriz
   */
  public Matrix(T[][] values)
  {
    this.values = values;
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial10.exercicio32.
   *      Container#getIterator()
   */
  @Override
  public Iterator<T> getIterator()
  {
    return new MatrixIterator();
  }
}

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.exercicio32;

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

  }

  /**
   * Metodo principal da linguagem de programacao Java
   *
   * @param args argumentos da linha de comando (nao utilizado)
   */
  public static void main(String[] args)
  {
    Integer[][] values = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

    Matrix<Integer> matrix = new Matrix<Integer>(values);

    Iterator<Integer> iterator = matrix.getIterator();

    while(iterator.hasNext())
    {
      System.out.println(iterator.next());
    }
  }
}

Saída da Solução em Java

1
2
3
4
5
6
7
8
9

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