Is this how adapter design pattern used?
I have Draw class (implements Shapes) and Square class (implements Polygon). Now if both Draw and Square are closed to modifications and I need a square object created by the client to do the "drawing" then I go for an adapter.
Also is the below implementation object adapter pattern or the class adapter pattern?
interface Shapes {
public void draw();
}
class Draw implements Shapes {
@Override
public void draw() {
println("Drawing a shape");
}
}
interface Polygon {
public void getSides();
public void getArea();
}
class Square implements Polygon {
int length;
Square(int length){
this.length = length;
}
@Override
public void getSides() {
println("Sides: 4");
}
@Override
public void getArea() {
println("Area: "+length*length);
}
}
class SquareAdapter extends Square{
Shapes shape;
public SquareAdapter(Shapes shape, int length){
super(length);
this.shape = shape;
}
public void draw(){
shape.draw();
}
}
Client code:
SquareAdapter adapter = new SquareAdapter(new Draw(), 3);
adapter.draw();
adapter.getArea();
adapter.getSides();
Aucun commentaire:
Enregistrer un commentaire