设计模式之 Adapter

本文通过生动的例子介绍了适配器模式的两种实现方式——类适配器与对象适配器。类适配器通过继承机制将原有接口转换为所需的新接口,而对象适配器则通过组合的方式达到同样的目的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

类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面前闪亮登场了,骗过她的眼睛没有问题了,但是实际上他们依然是坏男孩。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值