Difference between revisions of "Composite (padrão de desenho)/Exercício 3: Construção e Visualização de Páginas"

From Wiki**3

< Composite (padrão de desenho)
(New page: = Problema = Uma página é constituída por vários elementos, que podem, ou não, ter eles próprios estrutura: imagens (são elementos atómicos que representam entidades gráficas); b...)
 
(Classe Page)
 
(20 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
{{TOCright}}
 
= Problema =
 
= Problema =
  
Line 4: Line 5:
  
 
= Solução =
 
= Solução =
 +
 +
A solução contempla uma classe abstracta, que representa os elementos em geral, e uma classe concreta para cada conceito.
 +
 +
Na implementação que se apresenta abaixo, as páginas podem conter outras páginas.
 +
 +
== Classe PageElement ==
 +
 +
<source lang="java">
 +
/**
 +
* This is an abstract page element.
 +
*/
 +
public abstract class PageElement {
 +
/**
 +
* @return "graphical" version of the element.
 +
*/
 +
public abstract String render();
 +
}
 +
</source>
 +
 +
== Classe Image ==
 +
 +
Uma representação abstracta de uma imagem.
 +
 +
<source lang="java">
 +
/** An image representation. */
 +
public class Image extends PageElement {
 +
 +
/** @see PageElement#render() */
 +
@Override
 +
public String render() {
 +
return "<image></image>";
 +
}
 +
 +
}
 +
</source>
 +
 +
== Classe TextBlock ==
 +
 +
Esta classe representa um bloco de texto.
 +
 +
<source lang="java">
 +
/** A simple text block. */
 +
public class TextBlock extends PageElement {
 +
 +
/** Text in this block. */
 +
private String _text = "";
 +
 +
/** @param text the text. */
 +
public TextBlock(String text) {
 +
_text = text;
 +
}
 +
 +
/** @see PageElement#render() */
 +
@Override
 +
public String render() {
 +
return "<textblock>" + _text + "</textblock>";
 +
}
 +
 +
}
 +
</source>
 +
 +
== Classe Paragraph ==
 +
 +
Esta classe representa um conjunto de blocos de texto formando um parágrafo.
 +
 +
<source lang="java">
 +
import java.util.ArrayList;
 +
import java.util.List;
 +
 +
/** A paragraph has several text blocks. */
 +
public class Paragraph extends PageElement {
 +
 +
/** Text blocks in this paragraph. */
 +
List<TextBlock> _textBlocks = new ArrayList<>();
 +
 +
/** @param textBlock the text block to be added. */
 +
void addTextBlock(TextBlock textBlock) {
 +
_textBlocks.add(textBlock);
 +
}
 +
 +
/** @see PageElement#render() */
 +
@Override
 +
public String render() {
 +
String text = "<paragraph>\n";
 +
for (TextBlock textBlock : _textBlocks)
 +
text += textBlock.render() + "\n";
 +
text += "</paragraph>";
 +
return text;
 +
}
 +
}
 +
</source>
 +
 +
== Classe Figure ==
 +
 +
Uma figura contém múltiplos elementos gráficos e uma legenda.
 +
 +
<source lang="java">
 +
import java.util.ArrayList;
 +
import java.util.List;
 +
 +
/** A figure with images and a caption. */
 +
public class Figure extends PageElement {
 +
/** Images in this figure. */
 +
List<Image> _images = new ArrayList<>();
 +
 +
/** Caption for this figure. */
 +
TextBlock _caption = new TextBlock("");
 +
 +
/**
 +
* @param image the image to be added
 +
*/
 +
void addImage(Image image) {
 +
_images.add(image);
 +
}
 +
 +
/**
 +
* @param caption the caption
 +
*/
 +
void setLegend(TextBlock caption) {
 +
_caption = caption;
 +
}
 +
 +
/** @see Element#render() */
 +
@Override
 +
public String render() {
 +
String text = "<figure>\n";
 +
for (Image image : _images)
 +
text += image.render() + "\n";
 +
text += _caption.render() + "\n";
 +
text += "</figure>";
 +
return text;
 +
}
 +
}
 +
</source>
 +
 +
== Classe Page ==
 +
 +
Classe que representa uma página. Uma página pode conter qualquer elemento, inclusivamente outras páginas.
 +
 +
<source lang="java">
 +
import java.util.ArrayList;
 +
import java.util.List;
 +
 +
/** A page is itself a page element. */
 +
public class Page extends PageElement {
 +
 +
/** Elements in this page (note that we admit recursive pages). */
 +
private List<PageElement> _elements = new ArrayList<>();
 +
 +
/** @param element element to be added to the page. */
 +
public void addElement(PageElement element) {
 +
_elements.add(element);
 +
}
 +
 +
/** @see Element#render() */
 +
@Override
 +
public String render() {
 +
String text = "<page>\n";
 +
for (PageElement element : _elements)
 +
text += element.render() + "\n";
 +
text += "</page>";
 +
return text;
 +
}
 +
}
 +
</source>
 +
 +
== Classe App ==
 +
 +
Aplicação exemplo.
 +
 +
<source lang="java">
 +
/**
 +
* Simple application.
 +
*/
 +
public class App {
 +
 +
/**
 +
* @param args
 +
*/
 +
public static void main(String[] args) {
 +
Page page = new Page();
 +
Paragraph p1 = new Paragraph();
 +
p1.addTextBlock(new TextBlock("Início."));
 +
p1.addTextBlock(new TextBlock("Segundo bloco com palavras,"));
 +
Image i1 = new Image();
 +
Image i2 = new Image();
 +
Figure figure = new Figure();
 +
figure.addImage(i1);
 +
figure.setLegend(new TextBlock("Imagem na figura."));
 +
page.addElement(p1);
 +
page.addElement(figure);
 +
page.addElement(i2);
 +
System.out.println(page.render());
 +
}
 +
 +
}
 +
</source>
 +
 +
= Compilação e Execução =
 +
 +
== Compilação ==
 +
 +
== Execução ==
 +
 +
java App
 +
 +
Resultado:
 +
<source lang="xml">
 +
<page>
 +
<paragraph>
 +
<textblock>Início.</textblock>
 +
<textblock>Segundo bloco com palavras,</textblock>
 +
</paragraph>
 +
<figure>
 +
<image></image>
 +
<textblock>Imagem na figura.</textblock>
 +
</figure>
 +
<image></image>
 +
</page>
 +
</source>
  
 
[[category:PO]]
 
[[category:PO]]
 
[[category:Ensino]]
 
[[category:Ensino]]
 +
[[category:PO Exemplos]]

Latest revision as of 10:51, 18 October 2022

Problema

Uma página é constituída por vários elementos, que podem, ou não, ter eles próprios estrutura: imagens (são elementos atómicos que representam entidades gráficas); blocos de texto (elementos atómicos que apenas podem conter texto); figuras (contêm uma ou mais imagens e podem ter uma legenda - um bloco de texto); parágrafos (podem vários blocos de texto). A página pode conter um ou mais elementos dos apresentados anteriormente. Todos os elementos implementam o método render, que permite apresentar a página. Escreva um método main que crie uma página e lhe adicione múltiplos elementos, por forma a permitir exemplificar a funcionalidade.

Solução

A solução contempla uma classe abstracta, que representa os elementos em geral, e uma classe concreta para cada conceito.

Na implementação que se apresenta abaixo, as páginas podem conter outras páginas.

Classe PageElement

/**
 * This is an abstract page element.
 */
public abstract class PageElement {
	/**
	 * @return "graphical" version of the element.
	 */
	public abstract String render();
}

Classe Image

Uma representação abstracta de uma imagem.

/** An image representation. */
public class Image extends PageElement {

	/** @see PageElement#render() */
	@Override
	public String render() {
		return "<image></image>";
	}

}

Classe TextBlock

Esta classe representa um bloco de texto.

/** A simple text block. */
public class TextBlock extends PageElement {

	/** Text in this block. */
	private String _text = "";

	/** @param text the text. */
	public TextBlock(String text) {
		_text = text;
	}

	/** @see PageElement#render() */
	@Override
	public String render() {
		return "<textblock>" + _text + "</textblock>";
	}

}

Classe Paragraph

Esta classe representa um conjunto de blocos de texto formando um parágrafo.

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

/** A paragraph has several text blocks. */
public class Paragraph extends PageElement {

	/** Text blocks in this paragraph. */
	List<TextBlock> _textBlocks = new ArrayList<>();

	/** @param textBlock the text block to be added. */
	void addTextBlock(TextBlock textBlock) {
		_textBlocks.add(textBlock);
	}

	/** @see PageElement#render() */
	@Override
	public String render() {
		String text = "<paragraph>\n";
		for (TextBlock textBlock : _textBlocks)
			text += textBlock.render() + "\n";
		text += "</paragraph>";
		return text;
	}
}

Classe Figure

Uma figura contém múltiplos elementos gráficos e uma legenda.

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

/** A figure with images and a caption. */
public class Figure extends PageElement {
	/** Images in this figure. */
	List<Image> _images = new ArrayList<>();

	/** Caption for this figure. */
	TextBlock _caption = new TextBlock("");

	/**
	 * @param image the image to be added
	 */
	void addImage(Image image) {
		_images.add(image);
	}

	/**
	 * @param caption the caption
	 */
	void setLegend(TextBlock caption) {
		_caption = caption;
	}

	/** @see Element#render() */
	@Override
	public String render() {
		String text = "<figure>\n";
		for (Image image : _images)
			text += image.render() + "\n";
		text += _caption.render() + "\n";
		text += "</figure>";
		return text;
	}
}

Classe Page

Classe que representa uma página. Uma página pode conter qualquer elemento, inclusivamente outras páginas.

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

/** A page is itself a page element. */
public class Page extends PageElement {

	/** Elements in this page (note that we admit recursive pages). */
	private List<PageElement> _elements = new ArrayList<>();

	/** @param element element to be added to the page. */
	public void addElement(PageElement element) {
		_elements.add(element);
	}
	
	/** @see Element#render() */
	@Override
	public String render() {
		String text = "<page>\n";
		for (PageElement element : _elements)
			text += element.render() + "\n";
		text += "</page>";
		return text;
	}
}

Classe App

Aplicação exemplo.

/**
 * Simple application.
 */
public class App {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Page page = new Page();
		Paragraph p1 = new Paragraph();
		p1.addTextBlock(new TextBlock("Início."));
		p1.addTextBlock(new TextBlock("Segundo bloco com palavras,"));
		Image i1 = new Image();
		Image i2 = new Image();
		Figure figure = new Figure();
		figure.addImage(i1);
		figure.setLegend(new TextBlock("Imagem na figura."));
		page.addElement(p1);
		page.addElement(figure);
		page.addElement(i2);
		System.out.println(page.render());
	}

}

Compilação e Execução

Compilação

Execução

java App

Resultado:

 <page>
 <paragraph>
 <textblock>Início.</textblock>
 <textblock>Segundo bloco com palavras,</textblock>
 </paragraph>
 <figure>
 <image></image>
 <textblock>Imagem na figura.</textblock>
 </figure>
 <image></image>
 </page>