作者:whisper
链接:http://proprogrammar.com:443/article/443
声明:请尊重原作者的劳动,如需转载请注明出处
有两种适配器模式:类的适配器和对象的适配器
类的适配器是继承要适配的类,对象的适配器是关联要适配的类的对象,类的适配器继承了要适配的类,就不能继承其它类了,而对象的适配器不但能继承其它类,还能适配其子类,所以觉得对象的适配器适用范围要大一些,下面就说说对象的适配器模式
一个人到德国旅行,带了个国标的充电器,但德国要用德标的充电器,所以他又带了一个适配器
package constructional.pattern.adapter;
public interface DBSocketInterface {
void output();
}
package constructional.pattern.adapter;
public class DBSocket implements DBSocketInterface {
@Override
public void output() {
System.out.println("two round Angle output current, charge German equipment.");
}
}
package constructional.pattern.adapter;
public interface GBSocketInterface {
void output();
}
package constructional.pattern.adapter;
public class GBSocket implements GBSocketInterface {
@Override
public void output() {
System.out.println("three plat angle output current. charge China equipment.");
}
}
package constructional.pattern.adapter;
public class SocketAdapter implements DBSocketInterface {
private GBSocketInterface gBSocketInterface;
public SocketAdapter(GBSocketInterface gBSocketInterface) {
this.gBSocketInterface = gBSocketInterface;
}
@Override
public void output() {
System.out.println("insert into two round hole and three plat"
+ " angle can be inserted to output current.");
gBSocketInterface.output();
}
}
package constructional.pattern.adapter;
public class Hotel {
private DBSocketInterface dbSocketInterface;
public Hotel(DBSocketInterface dbSocketInterface) {
super();
this.dbSocketInterface = dbSocketInterface;
}
public void charge()
{
dbSocketInterface.output();
}
}
适配器继承了德标的接口,但用来适配国标的充电器,即把国标的充电器和德标的标准结合起来
下面看一下测试代码
package constructional.pattern.adapter;
public class TestSocketClass {
public static void main(String[] args) {
// 1.德国电器
DBSocketInterface dbSocket = new DBSocket();
Hotel hotel = new Hotel(dbSocket);
hotel.charge();
System.out.println("----------------------------------------------------------------");
// 2.中国电器
GBSocketInterface gBSocket = new GBSocket();
SocketAdapter socketAdapter = new SocketAdapter(gBSocket);
Hotel hotel2 = new Hotel(socketAdapter);
hotel2.charge();
}
}
运行结果如下
亲爱的读者:有时间可以点赞评论一下
全部评论