适配器(Adapter)模式将一个类的接口转换成客户希望的另外一个接口,能够使得原本由于接口不兼容而不能一起工作的那些类可以协同工作了。
package JAVA_Project_01_05;
interface Shape {
public void setPosition(int position);
public int getPositioin();
public void move();
public void display();
}
class Oblong implements Shape {
int position;
public void setPosition(int position) {
this.position = position;
}
public int getPositioin() {
return this.position;
}
public void move() {
System.out.println("矩形图形已经移动到:" + 3 * position);
}
public void display() {
System.out.println("矩形图形的位置:" + position);
}
}
class Circular {
int position;
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public void display() {
System.out.println("圆形图形的位置:" + position);
}
}
class CircularAdapter implements Shape {
private Circular circular;
public CircularAdapter() {
circular = new Circular();
}
public void display() {
circular.display();
}
public int getPositioin() {
return circular.getPosition();
}
public void move() {
System.out.println("圆形图形已经移动到:" + 3 * getPositioin());
}
public void setPosition(int position) {
circular.setPosition(position);
}
}
public class TextAdapter {
public static void main(String[] args) {
Oblong oblong = new Oblong();
oblong.setPosition(100);
oblong.display();
oblong.move();
CircularAdapter circular = new CircularAdapter();
circular.setPosition(200);
circular.display();
circular.move();
}
}