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接口开始工作");
}
}