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

Quando uma abstração pode ter uma entre várias implementações possíveis, a maneira usual de acomodá-las é usando a herança. Uma classe abstrata define a interface para a abstração, e subclasses concretas a implementam de formas diferentes. Mas essa abordagem nem sempre é suficientemente flexível. A herança liga uma implementação à abstração permanentemente, o que torna difícil modificar, aumentar e reutilizar abstrações e implementações independentemente.

Empregando o padrão de projeto Bridge, desenvolva um sistema estatístico que permita ao usuário selecionar o método a ser utilizado para o calculo da média de uma série de números, que podem ser fornecidos pelo usuário por meio de um vetor, uma matriz, uma lista dentre diversas outras formas.

 

Diagrama de Classes na Linguagem de Programação Java Mean.java ArithmeticMean.java GeometricMean.java HarmonicMean.java Element.java ElementList.java ElementVector.java Application.java
Diagrama de Classes
Diagrama de Classes na Linguagem de Programação Java

Arquivo Mean.java

/*************************************************************************
 * Copyright (C) 2009/2018 - 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.exercicio26;

/**
 * Interface para a realizacao da media sobre um conjunto de elementos
 * 
 * Implementor define a interface para as classes de implementacao. Esta
 * interface nao precisa corresponder exatamente a interface de Abstraction;
 * de fato, as duas interfaces podem ser bem diferentes. A interface de
 * Implementor fornece somente operacoes primitivas e Abstraction define
 * operacoes de nivel mais alto baseadas nestas primitivas (Gamma, 2000)
 */
public interface Mean
{
  /**
   * Realizar a media dos elementos
   *
   * @param values elementos
   * @return media dos elementos
   */
  public double average(Object[] values);
}

Arquivo ArithmeticMean.java

/*************************************************************************
 * Copyright (C) 2009/2018 - 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.exercicio26;

/**
 * Realizar a media aritmetica
 *
 * ConcreteImplementor implementa a interface de Implementor e define sua
 * implementacao concreta (Gamma, 2000)
 */
public class ArithmeticMean implements Mean
{
  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial09.exercicio26.Mean#calculate(java.lang.Object[])
   */
  @Override
  public double average(Object[] values)
  {
    double sum = 0.0;

    int count = 0;

    for(Object value : values)
    {
      if(value instanceof Number)
      {
        sum = sum + ((Number) value).doubleValue();

        count = count + 1;
      }
    }

    return sum / count;
  }
}

Arquivo GeometricMean.java

/*************************************************************************
 * Copyright (C) 2009/2018 - 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.exercicio26;

/**
 * Realizar a media geometrica
 *
 * ConcreteImplementor implementa a interface de Implementor e define sua
 * implementacao concreta (Gamma, 2000)
 */
public class GeometricMean implements Mean
{
  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial09.exercicio26.Mean#calculate(java.lang.Object[])
   */
  @Override
  public double average(Object[] values)
  {
    int amount = 0;

    double product = 1.0;

    for(Object value : values)
    {
      if(value instanceof Number)
      {
        amount = amount + 1;

        product = product * ((Number) value).doubleValue();
      }
    }

    return Math.pow(product, 1.0/amount);
  }
}

Arquivo HarmonicMean.java

/*************************************************************************
 * Copyright (C) 2009/2018 - 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.exercicio26;

/**
 * Realizar a media harmonica
 *
 * ConcreteImplementor implementa a interface de Implementor e define sua
 * implementacao concreta (Gamma, 2000)
 */
public class HarmonicMean implements Mean
{
  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial09.exercicio26.Mean#calculate(java.lang.Object[])
   */
  @Override
  public double average(Object[] values)
  {
    int amount = 0;

    double sum = 0.0;

    for(Object value : values)
    {
      if(value instanceof Number)
      {
        amount = amount + 1;

        sum = sum + 1.0/((Number) value).doubleValue();;
      }
    }

    return amount / sum; 
  }
}

Arquivo Element.java

/*************************************************************************
 * Copyright (C) 2009/2018 - 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.exercicio26;

/**
 * Elementos utilizados para o calculo da media
 *
 * Abstraction define a interface da abstracao, mantendo uma referencia
 * para um objeto do tipo Implementor (Gamma, 2000)
 */
public abstract class Element
{
  /**
   * Representacao da media
   */
  protected Mean mean;

  /**
   * Inicializar a media a ser empregada
   *
   * @param mean media a ser empregada
   */
  protected Element(Mean mean)
  {
    this.mean = mean;
  }

  /**
   * Retorna a media dos elementos
   *
   * @return media dos elementos
   */
  public abstract double getMean(); 
}

Arquivo ElementList.java

/*************************************************************************
 * Copyright (C) 2009/2018 - 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.exercicio26;

import java.util.List;

/**
 * Elementos armazenados numa lista
 *
 * RefinedAbstraction estende a interface definida por
 * Abstraction (Gamma, 2000)
 */
public class ElementList<T> extends Element
{
  /**
   * Elementos
   */
  private List<T> values;

  /**
   * Inicializar os elementos e a media a ser empregada
   *
   * @param values elementos
   * @param mean media a ser empregada
   */
  public ElementList(List<T> values, Mean mean)
  {
    super(mean);

    this.values = values;
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial09.exercicio26.Number#getMean()
   */
  @Override
  public double getMean()
  {
    return mean.average(values.toArray());
  }
}

Arquivo ElementVector.java

/*************************************************************************
 * Copyright (C) 2009/2018 - 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.exercicio26;

/**
 * Elementos armazenados num vetor
 *
 * RefinedAbstraction estende a interface definida por
 * Abstraction (Gamma, 2000)
 */
public class ElementVector extends Element
{
  /**
   * Elementos
   */
  private Object[] values;

  /**
   * Inicializar os elementos e a media a ser empregada
   *
   * @param values elementos
   * @param mean media a ser empregada
   */
  public ElementVector(Object[] values, Mean mean)
  {
    super(mean);

    this.values = values;
  }

  /* (non-Javadoc)
   * @see com.ybadoo.tutoriais.poo.tutorial09.exercicio26.Number#getMean()
   */
  @Override
  public double getMean()
  {
    return mean.average(values);
  }
}

Arquivo Application.java

/*************************************************************************
 * Copyright (C) 2009/2018 - 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.exercicio26;

import java.util.ArrayList;
import java.util.List;

/**
 * Classe responsavel pela execucao do padrao Bridge
 */
public class Application
{
  /**
   * Construtor para inicializar a execucao do padrao Bridge
   */
  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};

    Element vector = new ElementVector(values, new ArithmeticMean());

    System.out.println(vector.getMean());

    List<Integer> listValues = new ArrayList<Integer>();
    listValues.add(1);
    listValues.add(2);
    listValues.add(3);
    listValues.add(4);
    listValues.add(5);

    Element list = new ElementList<Integer>(listValues, new ArithmeticMean());

    System.out.println(list.getMean());
  }
}

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