您的位置:首页 > 其它

设计模式学习:适配器

2017-06-06 18:04 148 查看
听起来很高大,但在开发中常见的不能再常见了。主要的思想就是将一个类的接口转换成另外一个希望的接口。听起来有些拗口。下面的例子可以很好地解释这句话。

欧洲的插头一般是3口的,而国内是2口的,虽然同样都是充电,但三口的无法在2口的插排上充电,这时就需要一个转接口,这个转接口就是适配器。接下来就实现让三口的插头在2口的插排上充电。

首先,定义3口和2口插头的接口:

//3口
public interface ThreeSocket
{
void ThreeSocketCharge();
}

//2口
public interface DoubleSocket
{
void DoubleSocketCharge();
}


然后实现各自的充电方法:

//2口的充电方法
public class MyDoubleSocket implements DoubleSocket {

@Override
public void DoubleSocketCharge()
{
System.out.println("DoubleSocketCharge");
}

}

//3口的充电方法
public class MyThreeSocket implements ThreeSocket {

@Override
public void ThreeSocketCharge()
{
System.out.println("ThreeSockerCharge");
}

}


接下来就是适配器类,他实现了将3口插头在2口插排上的充电方法。

public class MyAdapter implements DoubleSocket
{
ThreeSocket threesocket;
public MyAdapter(ThreeSocket threesocket)
{
this.threesocket=threesocket;
}
@Override
public void DoubleSocketCharge()
{
this.threesocket.ThreeSocketCharge();
System.out.println("将3口充电改装成了2口充电");
}

}


测试:

public class test {

public static void main(String[] args)
{
DoubleSocket doubleSocket=new MyDoubleSocket();
doubleSocket.DoubleSocketCharge();

ThreeSocket threeSocket=new MyThreeSocket();
threeSocket.ThreeSocketCharge();

MyAdapter adapter=new MyAdapter(threeSocket);
adapter.DoubleSocketCharge();
}

}


测试结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: