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

Desenvolva um programa que receba um texto qualquer de entrada. O texto deve ser lido caractere por caractere e as seguintes estatísticas devem ser impressas sobre:

• a) o número de espaços encontrados;

• b) o número de letras 'a';

• c) o número de pontos.

Use Chain of Responsibility e faça com que cada tipo de caractere seja tratado por um elo diferente da corrente.

 

Arquivo Character.java

/**
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.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 copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

/**
 * Handler
 * 
 * Define uma interface para tratar solicitacoes
 * Implementa o elo ao sucessor
 */
public abstract class Character
{
  /**
   * Quantidade de caracteres
   */
  private int amount;
  
  /**
   * Proximo elemento da sequencia
   */
  private Character successor;
  
  public Character()
  {
    this.successor = null;
    
    this.amount = 0;
  }
  
  /**
   * Incrementar a quantidade de caracteres
   */
  public void addAmount()
  {
    this.amount = this.amount + 1;
  }

  /**
   * Retornar a quantidade de caracteres
   * 
   * @return quantidade de caracteres
   */
  public int getAmount()
  {
    return this.amount;
  }

  /**
   * Retornar o proximo elemento da sequencia
   * 
   * @return proximo elemento da sequencia
   */
  protected Character getSuccessor()
  {
    return this.successor;
  }
  
  /**
   * Processar a requisicao
   * 
   * @param letter letra a ser processada
   */
  public abstract void processRequest(char letter);
  
  /**
   * Definir o elemento sucessor da sequencia
   * 
   * @param successor proximo elemento da sequencia
   */
  public void setSuccessor(Character successor)
  {
    this.successor = successor;
  }
}

Arquivo ALetter.java

/**
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.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 copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

/**
 * ConcreteHandler
 * 
 * Trata de solicitacoes pelas quais e responsavel
 * Pode acessar seu sucessor
 * Se o ConcreteHandler pode tratar a solicitacao, ele assim o faz;
 * caso contrario, ele repassa a solicitacao para o seu sucessor
 */
public class ALetter extends Character
{
  /* (non-Javadoc)
   * @see com.ybadoo.Character#processRequest(char)
   */
  public void processRequest(char letter)
  {
    if(letter == 'a')
    {
      addAmount();
    }
    else
    {
      if(getSuccessor() != null)
      {
        getSuccessor().processRequest(letter);
      }
    }
  }
  
  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  public String toString()
  {
    return "a letters: " + getAmount();
  }
}

Arquivo SpaceLetter.java

/**
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.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 copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

/**
 * ConcreteHandler
 * 
 * Trata de solicitacoes pelas quais e responsavel
 * Pode acessar seu sucessor
 * Se o ConcreteHandler pode tratar a solicitacao, ele assim o faz;
 * caso contrario, ele repassa a solicitacao para o seu sucessor
 */
public class SpaceLetter extends Character
{
  /* (non-Javadoc)
   * @see com.ybadoo.Character#processRequest(char)
   */
  public void processRequest(char letter)
  {
    if(letter == ' ')
    {
      addAmount();
    }
    else
    {
      if(getSuccessor() != null)
      {
        getSuccessor().processRequest(letter);
      }
    }
  }
  
  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  public String toString()
  {
    return "Space letters: " + getAmount();
  }
}

Arquivo PointLetter.java

/**
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.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 copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

/**
 * ConcreteHandler
 * 
 * Trata de solicitacoes pelas quais e responsavel
 * Pode acessar seu sucessor
 * Se o ConcreteHandler pode tratar a solicitacao, ele assim o faz;
 * caso contrario, ele repassa a solicitacao para o seu sucessor
 */
public class PointLetter extends Character
{
  /* (non-Javadoc)
   * @see com.ybadoo.Character#processRequest(char)
   */
  public void processRequest(char letter)
  {
    if(letter == '.')
    {
      addAmount();
    }
    else
    {
      if(getSuccessor() != null)
      {
        getSuccessor().processRequest(letter);
      }
    }
  }
  
  /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  public String toString()
  {
    return "Point letters: " + getAmount();
  }
}

Arquivo Application.java

/**
 * Copyright (C) 2009/2024 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.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 copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

/**
 * Client
 * 
 * Inicia a solicitacao para um objeto ConcreteHandler da cadeia
 */
public class Application
{
  /**
   * Metodo principal da linguagem de programacao Java
   * 
   * @param args argumentos da linha de comando (nao utilizado)
   */
  public static void main(String[] args)
  {
    Character aLetter = new ALetter();
    
    Character spaceLetter = new SpaceLetter();
    
    Character pointLetter = new PointLetter();
    
    aLetter.setSuccessor(spaceLetter);
    
    spaceLetter.setSuccessor(pointLetter);
    
    String test = "Chain of Responsibility.";
    
    for(int i = 0; i < test.length(); i++)
    {
      aLetter.processRequest(test.charAt(i));
    }
    
    System.out.println(aLetter.toString());
    System.out.println(spaceLetter.toString());
    System.out.println(pointLetter.toString());
  }
}