-
Notifications
You must be signed in to change notification settings - Fork 1
/
Facade.java
104 lines (89 loc) · 2.42 KB
/
Facade.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Facade pattern - build a 'console'
package structural.facade;
import java.util.ArrayList;
import java.util.List;
class Buffer
{
private char [] characters;
private int lineWidth;
public Buffer(int lineHeight, int lineWidth)
{
this.lineWidth = lineWidth;
characters = new char[lineWidth*lineHeight]; // specify size of buffer
}
public char charAt(int x, int y)
{
return characters[y*lineWidth+x];
}
}
class Viewport
{
private final Buffer buffer;
private final int width;
private final int height;
private final int offsetX;
private final int offsetY;
public Viewport(Buffer buffer, int width, int height,
int offsetX, int offsetY)
{
this.buffer = buffer;
this.width = width;
this.height = height;
this.offsetX = offsetX;
this.offsetY = offsetY;
}
public char charAt(int x, int y)
{
return buffer.charAt(x+offsetX, y+offsetY);
}
}
class Console
{
private List<Viewport> viewports = new ArrayList<>();
int width, height;
public Console(int width, int height) {
this.width = width;
this.height = height;
}
public void addViewport(Viewport viewport)
{
viewports.add(viewport);
}
// Facade HERE
public static Console newConsole(int width, int height)
{
Buffer buffer = new Buffer(width, height);
Viewport viewport = new Viewport(buffer, width, height, 0, 0);
Console console = new Console(width, height);
console.addViewport(viewport);
return console;
}
public void render()
{
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
for(Viewport vp : viewports)
{
System.out.println(vp.charAt(x,y));
}
System.out.println();
}
}
}
}
class FacadeDemo
{
public static void main(String[] args) {
// Low level API. A lot of steps to go through to render the console
// Buffer buffer = new Buffer(30, 20);
// Viewport viewport = new Viewport(buffer, 30, 20, 0, 0);
// Console console = new Console(30, 20);
// console.addViewport(viewport);
// console.render();
// Using facade here.
Console console2 = Console.newConsole(30, 20);
console2.render();
}
}