1
這是如何使用適配器設計模式的?對象適配器模式的使用案例
我有Draw類(實現Shapes)和Square類(實現多邊形)。現在,如果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();
UPDATE 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();
請查看我添加爲編輯以上職位的答案。該示例代碼有意義嗎? – John
是的,它似乎是兩種適配器模式類型的正確用法,因爲在這種情況下,您可以使用適配器類作爲Shapes的實例 – Stanislav