-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdapterDesignPattern.java
More file actions
36 lines (30 loc) · 1 KB
/
AdapterDesignPattern.java
File metadata and controls
36 lines (30 loc) · 1 KB
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
// Step 1: Target interface that client expects
interface Shape {
void draw();
}
// Step 2: Adaptee class (Incompatible class we want to use)
class LegacyRectangle {
public void drawRectangle() {
System.out.println("Drawing a rectangle using LegacyRectangle");
}
}
// Step 3: Adapter class - makes LegacyRectangle compatible with Shape
class RectangleAdapter implements Shape {
private LegacyRectangle legacyRectangle;
public RectangleAdapter(LegacyRectangle legacyRectangle) {
this.legacyRectangle = legacyRectangle;
}
@Override
public void draw() {
// Translate Shape.draw() to LegacyRectangle.drawRectangle()
legacyRectangle.drawRectangle();
}
}
// Client code
public class Main {
public static void main(String[] args) {
LegacyRectangle legacyRectangle = new LegacyRectangle();
Shape shape = new RectangleAdapter(legacyRectangle); // Use adapter
shape.draw(); // Output: Drawing a rectangle using LegacyRectangle
}
}