这是使用适配器设计模式的吗?
我有Draw类(实现Shapes)和Square类(实现Polygon)。现在如果Draw和Square都不接受修改,我需要一个由客户端创建的方形对象来进行“绘图”,那么我就去找一个适配器。
以下是实现对象适配器模式还是类适配器模式?
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();
}
}
客户代码:
SquareAdapter adapter = new SquareAdapter(new Draw(), 3);
adapter.draw();
adapter.getArea();
adapter.getSides();
更新1:解决方案
感谢斯坦尼斯拉夫。我以更合适的方式修改了这个例子。
interface Draw {
public void draw();
}
class Circle implements Draw {
@Override
public void draw() {
println("Drawing a circle");
}
}
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);
}
}
//object composition adapters
class SquareAdapter implements Draw {
Polygon square;
public SquareAdapter(Polygon square){
this.square = square;
}
@Override
public void draw(){
println("Drawing a square");
}
public Polygon getSquare() {
return square;
}
}
客户代码:
Draw drawingObj = null;
//Now lets say the client wants to draw a Square but it
//doesn't implement Draw
//drawingObj = new Square();
//drawingObj.draw() //this is not possible so we write a adapter
drawingObj = new SquareAdapter(new Square(5));
drawingObj.draw();
((SquareAdapter) drawingObj).getSquare().getSides();
((SquareAdapter) drawingObj).getSquare().getArea();
//class inheritance adapters
class SquareAdapter extends Square implements Draw {
SquareAdapter(int length) {
super(length);
}
@Override
public void draw(){
println("Drawing a square");
}
}
客户代码:
Draw drawingObj = null;
//Now lets say the client wants to draw a Square but it
//doesn't implement Draw
//drawingObj = new Square();
//drawingObj.draw() //this is not possible so we write a adapter
drawingObj = new SquareAdapter(5);
drawingObj.draw();
((Square) drawingObj).getSides();
((Square) drawingObj).getArea();
答案 0 :(得分:0)
适配器模式旨在成为两个不兼容接口之间的桥梁,但不向现有对象添加新功能。在你的情况下
Draw和Square关闭修改,我需要一个由客户创建的方形对象来进行“绘图”
它似乎更像Decorator模式,旨在为现有对象创建新功能,而不改变它的内部结构。
因此,在Adapter模式的情况下,您的Adapter类必须实现Shapes接口,而您希望它具有draw方法。虽然有两种类型的适配器 - 类和对象适配器,但它们都需要接口实现。
这是最简单的Adapter实现:
class SquareAdapter implements Shapes{
Polygon square;
public SquareAdapter(Polygon square){
this.square = square;
}
public void draw(){
//some logic to draw Square object
}
}