Aplicações costumam utilizar arquivos de propriedades para o armazenamento de suas configurações, como por exemplo, o endereço do banco de dados utilizado pela aplicação, o login e a senha de acesso ao respectivo banco de dados, o layout padrão da aplicação, o idioma padrão e assim por diante.
As informações no arquivo de propriedades são armazenadas no formato chave=valor, com cada par de informação ocupando uma respectiva linha, como por exemplo:
database=jdbc:postgresql://localhost:5432/ybadoo
user=root
password=123456
Empregando o padrão de projeto Proxy, desenvolva uma aplicação que carregue para a memória os registros contidos no arquivo de propriedades, de forma que a aplicação não precise abrir/fechar o arquivo para a recuperação de cada informação.
Para verificar o funcionamento do padrão de projeto Proxy, apresente a execução da aplicação com e sem a utilização do Proxy, informando ao usuário cada abertura/fechamento do arquivo de propriedades.
/*************************************************************************
* Copyright (C) 2009/2025 - 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.exercicio25;
/**
* Interface com a definicao dos metodos para a
* recuperacao das propriedades
*
* Subject define uma interface comum para RealSubject e Proxy,
* de maneira que um Proxy possa ser usado em qualquer lugar em
* que um RealSubject eh esperado (Gamma, 2000).
*/
public interface PropertiesInterface
{
/**
* Recuperar uma propriedade
*
* @param key chave da propriedade
* @return valor da propriedade
*/
public String getProperty(String key);
}
/*************************************************************************
* Copyright (C) 2009/2025 - 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.exercicio25;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Classe responsavel pela leitura do arquivo de propriedades
*
* RealSubject define o objeto real que o Proxy representa (Gamma, 2000).
*/
public class PropertiesFile implements PropertiesInterface
{
/**
* Arquivo de propriedades
*/
private String filename;
/**
* Inicializar o arquivo de propriedades
*
* @param filename arquivo de propriedades
*/
public PropertiesFile(String filename)
{
this.filename = filename;
}
/* (non-Javadoc)
* @see com.ybadoo.tutoriais.poo.tutorial09.exercicio25.
* PropertiesInterface#getProperty(java.lang.String)
*/
public String getProperty(String key)
{
Properties properties = new Properties();
System.out.println("Abrindo o arquivo de propriedades");
try
{
InputStream inputStream = new FileInputStream(filename);
properties.load(inputStream);
inputStream.close();
}
catch(IOException exception)
{
exception.printStackTrace();
}
System.out.println("Fechando o arquivo de propriedades");
return properties.getProperty(key);
}
}
/*************************************************************************
* Copyright (C) 2009/2025 - 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.exercicio25;
import java.util.Properties;
/**
* Classe responsavel pelo proxy do arquivo de propriedades
*
* Proxy mantem uma referencia que permite ao Proxy acessar o
* objeto real (RealSubject). O Proxy pode referenciar um
* Subject se as interfaces de RealSubject e Subject forem as
* mesmas. Fornece uma interface identica a de Subject, de
* modo que o Proxy possa substituir o objeto original
* (RealSubject) (Gamma, 2000).
*/
public class PropertiesProxy implements PropertiesInterface
{
/**
* Propriedades
*/
private Properties properties;
/**
* Leitura do arquivo de propriedades
*/
private PropertiesInterface propertiesFile;
/**
* Inicializar o arquivo de propriedades
*
* @param filename arquivo de propriedades
*/
public PropertiesProxy(String filename)
{
propertiesFile = new PropertiesFile(filename);
properties= new Properties();
}
/* (non-Javadoc)
* @see com.ybadoo.tutoriais.poo.tutorial09.exercicio25.
* PropertiesInterface#getProperty(java.lang.String)
*/
public String getProperty(String key)
{
if(!properties.containsKey(key))
{
properties.setProperty(key, propertiesFile.getProperty(key));
}
return properties.getProperty(key);
}
}
/*************************************************************************
* Copyright (C) 2009/2025 - 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.exercicio25;
/**
* Classe responsavel pela execucao do padrao Proxy
*/
public class Application
{
/**
* Construtor para inicializar a execucao do padrao Proxy
*/
private Application()
{
}
/**
* Metodo principal da linguagem de programacao Java
*
* @param args argumentos da linha de comando (nao utilizado)
*/
public static void main(String[] args)
{
String filename = "config.properties";
System.out.println("PropertiesFile Test");
System.out.println();
PropertiesInterface propertiesFile = new PropertiesFile(filename);
System.out.print("database: ");
System.out.println(propertiesFile.getProperty("database"));
System.out.println();
System.out.print("user: ");
System.out.println(propertiesFile.getProperty("user"));
System.out.println();
System.out.print("password: ");
System.out.println(propertiesFile.getProperty("password"));
System.out.println();
System.out.print("database: ");
System.out.println(propertiesFile.getProperty("database"));
System.out.println();
System.out.print("user: ");
System.out.println(propertiesFile.getProperty("user"));
System.out.println();
System.out.print("password: ");
System.out.println(propertiesFile.getProperty("password"));
System.out.println();
System.out.println();
System.out.println("PropertiesProxy Test");
System.out.println();
PropertiesInterface propertiesProxy = new PropertiesProxy(filename);
System.out.print("database: ");
System.out.println(propertiesProxy.getProperty("database"));
System.out.println();
System.out.print("user: ");
System.out.println(propertiesProxy.getProperty("user"));
System.out.println();
System.out.print("password: ");
System.out.println(propertiesProxy.getProperty("password"));
System.out.println();
System.out.print("database: ");
System.out.println(propertiesProxy.getProperty("database"));
System.out.println();
System.out.print("user: ");
System.out.println(propertiesProxy.getProperty("user"));
System.out.println();
System.out.print("password: ");
System.out.println(propertiesProxy.getProperty("password"));
System.out.println();
}
}
Gamma, Erich. (2000). Padrões de Projeto: soluções reutilizáveis de software orientado a objetos. Porto Alegre: Bookman. 364 páginas.