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)
(Classe Image)
(Classe Page)
 
(17 intermediate revisions by the same user not shown)
Line 12: Line 12:
 
== Classe PageElement ==
 
== Classe PageElement ==
  
<java5>
+
<source lang="java">
 
/**
 
/**
 
  * This is an abstract page element.
 
  * This is an abstract page element.
Line 22: Line 22:
 
public abstract String render();
 
public abstract String render();
 
}
 
}
</java5>
+
</source>
  
 
== Classe Image ==
 
== Classe Image ==
Line 28: Line 28:
 
Uma representação abstracta de uma imagem.
 
Uma representação abstracta de uma imagem.
  
<java5>
+
<source lang="java">
/**
+
/** An image representation. */
* An abstract image representation.
 
*/
 
 
public class Image extends PageElement {
 
public class Image extends PageElement {
  
/**
+
/** @see PageElement#render() */
* @see PageElement#render()
 
*/
 
 
@Override
 
@Override
@SuppressWarnings("nls")
 
 
public String render() {
 
public String render() {
 
return "<image></image>";
 
return "<image></image>";
Line 44: Line 39:
  
 
}
 
}
</java5>
+
</source>
  
 
== Classe TextBlock ==
 
== Classe TextBlock ==
Line 50: Line 45:
 
Esta classe representa um bloco de texto.
 
Esta classe representa um bloco de texto.
  
<java5>
+
<source lang="java">
/**
+
/** A simple text block. */
* A simple text block.
+
public class TextBlock extends PageElement {
*/
 
public class TextBlock extends Element {
 
  
/**
+
/** Text in this block. */
* Text in this block.
+
private String _text = "";
*/
 
private String _text;
 
  
/**
+
/** @param text the text. */
* @param text
 
*/
 
 
public TextBlock(String text) {
 
public TextBlock(String text) {
 
_text = text;
 
_text = text;
 
}
 
}
  
/**
+
/** @see PageElement#render() */
* @see Element#render()
 
*/
 
 
@Override
 
@Override
@SuppressWarnings("nls")
 
 
public String render() {
 
public String render() {
 
return "<textblock>" + _text + "</textblock>";
 
return "<textblock>" + _text + "</textblock>";
Line 78: Line 64:
  
 
}
 
}
</java5>
+
</source>
  
 
== Classe Paragraph ==
 
== Classe Paragraph ==
Line 84: Line 70:
 
Esta classe representa um conjunto de blocos de texto formando um parágrafo.
 
Esta classe representa um conjunto de blocos de texto formando um parágrafo.
  
<java5>
+
<source lang="java">
 
import java.util.ArrayList;
 
import java.util.ArrayList;
 +
import java.util.List;
  
/**
+
/** A paragraph has several text blocks. */
* A paragraph has several text blocks.
+
public class Paragraph extends PageElement {
*/
+
 
public class Paragraph extends Element {
+
/** Text blocks in this paragraph. */
/**
+
List<TextBlock> _textBlocks = new ArrayList<>();
* Text blocks in this paragraph.
 
*/
 
ArrayList<TextBlock> _textBlocks = new ArrayList<TextBlock>();
 
  
/**
+
/** @param textBlock the text block to be added. */
* @param textBlock
 
*/
 
 
void addTextBlock(TextBlock textBlock) {
 
void addTextBlock(TextBlock textBlock) {
 
_textBlocks.add(textBlock);
 
_textBlocks.add(textBlock);
 
}
 
}
  
/**
+
/** @see PageElement#render() */
* @see Element#render()
 
*/
 
 
@Override
 
@Override
@SuppressWarnings("nls")
 
 
public String render() {
 
public String render() {
 
String text = "<paragraph>\n";
 
String text = "<paragraph>\n";
Line 116: Line 95:
 
}
 
}
 
}
 
}
</java5>
+
</source>
  
 
== Classe Figure ==
 
== Classe Figure ==
Line 122: Line 101:
 
Uma figura contém múltiplos elementos gráficos e uma legenda.
 
Uma figura contém múltiplos elementos gráficos e uma legenda.
  
<java5>
+
<source lang="java">
 
import java.util.ArrayList;
 
import java.util.ArrayList;
 +
import java.util.List;
  
/**
+
/** A figure with images and a caption. */
* A figure with images and a caption.
+
public class Figure extends PageElement {
*/
+
/** Images in this figure. */
public class Figure extends Element {
+
List<Image> _images = new ArrayList<>();
/**
 
* Images in this figure.
 
*/
 
ArrayList<Image> _images = new ArrayList<Image>();
 
  
/**
+
/** Caption for this figure. */
* Legend for this figure.
+
TextBlock _caption = new TextBlock("");
*/
 
TextBlock _caption = new TextBlock(""); //$NON-NLS-1$
 
  
 
/**
 
/**
* @param image
+
* @param image the image to be added
 
*/
 
*/
 
void addImage(Image image) {
 
void addImage(Image image) {
Line 147: Line 121:
  
 
/**
 
/**
* @param legend
+
* @param caption the caption
 
*/
 
*/
void setLegend(TextBlock legend) {
+
void setLegend(TextBlock caption) {
_caption = legend;
+
_caption = caption;
 
}
 
}
  
/**
+
/** @see Element#render() */
* @see Element#render()
 
*/
 
 
@Override
 
@Override
@SuppressWarnings("nls")
 
 
public String render() {
 
public String render() {
 
String text = "<figure>\n";
 
String text = "<figure>\n";
Line 167: Line 138:
 
}
 
}
 
}
 
}
</java5>
+
</source>
  
 
== Classe Page ==
 
== Classe Page ==
Line 173: Line 144:
 
Classe que representa uma página. Uma página pode conter qualquer elemento, inclusivamente outras páginas.
 
Classe que representa uma página. Uma página pode conter qualquer elemento, inclusivamente outras páginas.
  
<java5>
+
<source lang="java">
 
import java.util.ArrayList;
 
import java.util.ArrayList;
 +
import java.util.List;
  
/**
+
/** A page is itself a page element. */
* A simple text block.
+
public class Page extends PageElement {
*/
 
public class Page extends Element {
 
  
/**
+
/** Elements in this page (note that we admit recursive pages). */
* Elements in this page (note that we admit recursive pages).
+
private List<PageElement> _elements = new ArrayList<>();
*/
 
private ArrayList<Element> _elements = new ArrayList<Element>();
 
  
/**
+
/** @param element element to be added to the page. */
* @param element element to be added to the page.
+
public void addElement(PageElement element) {
*/
 
public void addElement(Element element) {
 
 
_elements.add(element);
 
_elements.add(element);
 
}
 
}
 
 
/**
+
/** @see Element#render() */
* @see Element#render()
 
*/
 
 
@Override
 
@Override
@SuppressWarnings("nls")
 
 
public String render() {
 
public String render() {
 
String text = "<page>\n";
 
String text = "<page>\n";
for (Element element : _elements)
+
for (PageElement element : _elements)
 
text += element.render() + "\n";
 
text += element.render() + "\n";
 
text += "</page>";
 
text += "</page>";
Line 206: Line 169:
 
}
 
}
 
}
 
}
</java5>
+
</source>
  
 
== Classe App ==
 
== Classe App ==
Line 212: Line 175:
 
Aplicação exemplo.
 
Aplicação exemplo.
  
<java5>
+
<source lang="java">
 
/**
 
/**
 
  * Simple application.
 
  * Simple application.
Line 238: Line 201:
  
 
}
 
}
</java5>
+
</source>
  
 
= Compilação e Execução =
 
= Compilação e Execução =
Line 249: Line 212:
  
 
Resultado:
 
Resultado:
 
+
<source lang="xml">
 
  <page>
 
  <page>
 
  <paragraph>
 
  <paragraph>
Line 261: Line 224:
 
  <image></image>
 
  <image></image>
 
  </page>
 
  </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>