目的:
将一个类的接口转换成客户希望的另外一个接口。A d a p t e r 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
意图:
(目的和意图是不变的,摘自《设计模式迷你手册》电子版)
下面是一个Java版的示例
一、原理图:
二、示例代码
/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-8-2 14:43:46
* 源角色
*/
public class Adaptee {
public int get220v(){
return 220;
}
}
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-8-2 14:43:46
* 源角色
*/
public class Adaptee {
public int get220v(){
return 220;
}
}
/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-8-2 14:43:23
* 目标角色
*/
public interface Target {
int get110v();
int get220v();
}
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-8-2 14:43:23
* 目标角色
*/
public interface Target {
int get110v();
int get220v();
}
/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-8-2 14:43:07
* 适配器角色:扩展源角色,实现目标角色,从而使得目标角色改动时候,不用改动源角色,只要改动适配器
*/
public class Adapter extends Adaptee implements Target{
public int get110v(){
return 110;
}
}
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-8-2 14:43:07
* 适配器角色:扩展源角色,实现目标角色,从而使得目标角色改动时候,不用改动源角色,只要改动适配器
*/
public class Adapter extends Adaptee implements Target{
public int get110v(){
return 110;
}
}
/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-8-2 15:00:31
* 客户端
*/
public class Client {
public static void main(String rags[]) {
new Client().test();
}
public void test() {
Target target = new Adapter();
int v1 = target.get110v();
int v2 = target.get220v();
}
}
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2008-8-2 15:00:31
* 客户端
*/
public class Client {
public static void main(String rags[]) {
new Client().test();
}
public void test() {
Target target = new Adapter();
int v1 = target.get110v();
int v2 = target.get220v();
}
}
适配器通过扩展源角色,同时实现目标接口,从而满足了同时提供220v,110v电压的要求。
本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/90767,如需转载请自行联系原作者