-
Notifications
You must be signed in to change notification settings - Fork 1
/
ISP.java
113 lines (87 loc) · 2.07 KB
/
ISP.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
105
106
107
108
109
110
111
112
113
// Interface Segregation Principle (ISP)
package solidprinciples.isp;
import javax.print.Doc;
class Document {
}
interface Machine {
void print(Document d);
void fax(Document d);
void scan(Document d);
}
class MultiFunctionPrinter implements Machine {
@Override
public void print(Document d) {
//
}
@Override
public void fax(Document d) {
//
}
@Override
public void scan(Document d) {
//
}
}
class OldFashionedPrinter implements Machine {
@Override
public void print(Document d) {
//
}
@Override
public void fax(Document d) {
// cannot implement fax with old fashioned printers. What to do?
// Try throwing new exception
// throw new Exception();
// Problem is that you need to add that to method signature and it
// also propagates to interface
}
@Override
public void scan(Document d) {
// cannot implement fax with old fashioned printers. What to do?
}
}
// ISP Approach here
// Segregate/split Machine interface
interface Printer {
void print(Document d);
}
interface Scanner {
void scan(Document d);
}
// YAGNI = You Ain't Going to Need It
class JustAPrinter implements Printer {
@Override
public void print(Document d) {
//
}
}
// One way to implement multiple interfaces
class Photocopier implements Printer, Scanner {
@Override
public void print(Document d) {
//
}
@Override
public void scan(Document d) {
//
}
}
// Another approach is to create an interface that extends the simpler interfaces
interface MultiFunctionDevice extends Printer, Scanner {
}
class MultiFunctionMachine implements MultiFunctionDevice {
private Printer printer;
private Scanner scanner;
public MultiFunctionMachine(Printer printer) {
this.printer = printer;
this.scanner = scanner;
}
@Override
public void print(Document d) {
printer.print (d);
}
@Override
public void scan(Document d) {
scanner.scan(d);
}
}