您的位置:首页 > 编程语言 > Java开发

Java设计模式——适配器设计模式

2016-01-16 13:17 597 查看
1.定义

把一个类的接口转换成客户希望的另一种接口

适配器模式使原本不兼容而不能一起工作的类可以一起工作

2.代码示例

public class Adapter
{
public static void main(String[] args)
{
PowerA a = new PowerAImpl();
//a.connect();
intput(a);

PowerB b = new PowerBImpl();
//intput(b);//不能这么用,input方法只能接收PowerA的接口

PowerAdapter powerAdapter = new PowerAdapter(b);
intput(powerAdapter);
}

public static void intput(PowerA a)
{
a.connect();
}
}

//适配器
class PowerAdapter implements PowerA
{
private PowerB b;

public PowerAdapter(PowerB b)
{
this.b = b;
}

public void connect()
{
b.insert();
}
}

interface PowerA
{
public void connect();
}

class PowerAImpl implements PowerA
{
public void connect()
{
System.out.println("电源A接口开始工作");
}
}

interface PowerB
{
public void insert();
}

class PowerBImpl implements PowerB
{
public void insert()
{
System.out.println("电源B接口开始工作");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: