类Adapter
将一个类的已有的接口转换成用户需要的另外一种接口。
举例来说:比如一个女孩,她喜欢乖巧的男孩做男朋友,可是Boy A 是个淘气的男孩,不符合女孩的要求,因此,他必须换个乖巧的界面出现在女孩的面前,才能得到女孩的欢心。
class BadBoy {
public void beNaughtyBf(String str){
System.out.println("I am a naughty boyfriend for "+str);
}
}
class GoodBoy {
public void beGoodBf(String str){
System.out.println("I am a good boyfriend for "+str);
}
}
class Adapter extends GoodBoy {
private BadBoy boyA = new BadBoy();
public Adapter(BadBoy boyA){
this.boyA = boyA;
}
public void beGoodBf(String str){
boyA.beNaughtyBf(str);
}
}
public class AdapterClient{
public static void main(String[] args){
BadBoy boya = new BadBoy();
Adapter adapter = new Adapter(boya);
adapter.beGoodBf("Mary");
}
}
就这样Boy A 以一个乖孩子的界面出现在Mary的面前,蒙骗了她,取得了她的欢心,但事实上,他依然是一个淘气的男孩,打印出来,看看就知道了。
对象Adapter
你想使用一些已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口。对象适配器可以适配它的父类接口。
比如:有的坏男孩也有很多优点,有的会说流利的英文,有的篮球打的很好,他们都想取得女孩的欢心,这样就做一个Adapter把他们统统包装成好男孩,但一个一个包太麻烦了,就把他们统称为坏男孩,统一包装。
class GoodBoy {
public void beGoodBf(String str) {
System.out.println("I can be a good boyfriend for "+str);
}
}
class Adapter extends GoodBoy implements BadBoy {
public BadBoy badboy;
public Adapter(BadBoy boya) {
this.badboy = boya;
}
public void beBadBf(String str) {
System.out.println("I'll try my best to be a good one for "+str);
}
public void beGoodBf(String str){
badboy.beBadBf(str);
this.beBadBf(str);
}
}
interface BadBoy {
public void beBadBf(String str);
}
class BasketballBoy implements BadBoy {
public void beBadBf(String str) {
System.out.println("I can play basketball, but I am a bad boyfriend for "+str);
}
}
class EnglishBoy implements BadBoy {
public void beBadBf(String str) {
System.out.println("I can speak English, but I am a bad boyfriend for "+str);
}
}
class Girl {
public static void main(String[] args){
BadBoy boya = new EnglishBoy();
BadBoy boyb = new BasketballBoy();
Adapter adapter = new Adapter(boya);
Adapter adapter1 = new Adapter(boyb);
adapter.beGoodBf("Mary");
adapter1.beGoodBf("Mary");
}
}
这样,坏男孩都被包装成好男孩了,他们可以在Mary面前闪亮登场了,骗过她的眼睛没有问题了,但是实际上他们依然是坏男孩。