Adapter pattern is required in following scenario:
Say you have defined an interface I1
with method M1
and M2
C1
and C2
implements this interface I1
, now for C1
while implementing M1
and M2
you have found no help from other existing classes so you need to write all logic by yourself.
Now while implementing class C2
you have come across class C3
with methods M3
and M4
that can be used to implement M1
and M2
for C2
so to utilize those M3
and M4
in class C2
you extends class C3
and use M3
and M4
of C3
.
In this example C2
becomes Adapter class
and C3
becomes adaptee
package com.design.patterns;
public class AdapterExample {
public static void main(String[] args) {
Shape line = new LineShape();
line.draw();
Shape text = new TextShape();
text.draw();
}
}
//==Start from here
interface Shape{
public void draw();
}
class LineShape implements Shape{
@Override
public void draw() {
System.out.println("write some logic and draw line");
}
}
//Adapter
class TextShape extends TextView implements Shape{
@Override
public void draw() {
System.out.println("logic is already there in class TextView");
drawText();
}
}
// Adaptee
class TextView{
public void drawText() {
System.out.println("Drawing Text Shape");
}
}