(→Estrutura) |
(→Exemplo) |
||
Line 13: | Line 13: | ||
Composição de ''streams'' em Java | Composição de ''streams'' em Java | ||
− | [[category: | + | O seguinte exemplo ilustra a programação de um stream em Java: este stream vai ser aplicado como um decorator. |
+ | |||
+ | === Classe implementa o ''decorator'' === | ||
+ | |||
+ | public class LowerCaseInputStream extends FilterInputStream { | ||
+ | |||
+ | public LowerCaseInputStream(InputStream in) { | ||
+ | super(in); | ||
+ | } | ||
+ | |||
+ | public int '''read'''() throws IOException { | ||
+ | int c = super.read(); | ||
+ | return (c == -1 ? c : Character.toLowerCase((char)c)); | ||
+ | } | ||
+ | |||
+ | public int '''read'''(byte[] b, int offset, int len) throws IOException { | ||
+ | int result = super.'''read'''(b, offset, len); | ||
+ | for (int i = offset; i < offset+result; i++) { | ||
+ | b[i] = (byte)Character.toLowerCase((char)b[i]); | ||
+ | } | ||
+ | return result; | ||
+ | } | ||
+ | |||
+ | } | ||
+ | |||
+ | === Exemplo / Teste === | ||
+ | |||
+ | Este exemplo mostra a utilização da classe e a utilização transparente do método '''read'''. | ||
+ | |||
+ | public class InputTest { | ||
+ | |||
+ | public static void main(String[] args) throws IOException { | ||
+ | int c; | ||
+ | |||
+ | try { | ||
+ | |||
+ | InputStream in = | ||
+ | new '''LowerCaseInputStream'''( | ||
+ | new BufferedInputStream( | ||
+ | new FileInputStream("test.txt"))); | ||
+ | |||
+ | while ((c = in.'''read'''()) >= 0) | ||
+ | System.out.print((char)c); | ||
+ | |||
+ | in.close(); | ||
+ | |||
+ | } catch (IOException e) { | ||
+ | e.printStackTrace(); | ||
+ | } | ||
+ | } | ||
+ | |||
+ | } | ||
+ | |||
+ | [[category:OOP]] |
Material correspondente à aula 27.
O padrão "decorator" permite a adição dinamica de comportamento a um objecto.
O padrão decorator tem a seguinte estrutura de classes:
Composição de streams em Java
O seguinte exemplo ilustra a programação de um stream em Java: este stream vai ser aplicado como um decorator.
public class LowerCaseInputStream extends FilterInputStream {
public LowerCaseInputStream(InputStream in) { super(in); } public int read() throws IOException { int c = super.read(); return (c == -1 ? c : Character.toLowerCase((char)c)); } public int read(byte[] b, int offset, int len) throws IOException { int result = super.read(b, offset, len); for (int i = offset; i < offset+result; i++) { b[i] = (byte)Character.toLowerCase((char)b[i]); } return result; } }
Este exemplo mostra a utilização da classe e a utilização transparente do método read.
public class InputTest { public static void main(String[] args) throws IOException { int c; try { InputStream in = new LowerCaseInputStream( new BufferedInputStream( new FileInputStream("test.txt"))); while ((c = in.read()) >= 0) System.out.print((char)c); in.close(); } catch (IOException e) { e.printStackTrace(); } } }