作者:因情语写
链接:https://www.proprogrammar.com/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();
}
}
运行结果如下
亲爱的读者:有时间可以点赞评论一下
月份 | 原创文章数 |
---|---|
202206 | 4 |
202205 | 2 |
202204 | 1 |
202203 | 11 |
202201 | 2 |
202108 | 7 |
202107 | 3 |
202106 | 16 |
202105 | 10 |
202104 | 16 |
202103 | 56 |
202102 | 14 |
202010 | 3 |
202009 | 3 |
202008 | 7 |
202007 | 7 |
202006 | 10 |
202005 | 11 |
202004 | 22 |
202003 | 52 |
202002 | 44 |
202001 | 83 |
201912 | 52 |
201911 | 29 |
201910 | 41 |
201909 | 99 |
201908 | 35 |
201907 | 73 |
201906 | 121 |
201811 | 1 |
201810 | 2 |
201804 | 1 |
201803 | 1 |
201802 | 1 |
201707 | 1 |
全部评论