适配器模式

适配器模式

在计算机编程中,适配器模式(有时候也称包装样式或包装)将一个类的接口适配成用户所期待的。一个适配允许通常因为接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。

共有两种适配器模式

  • 类适配器模式
    这种适配器模式下,适配器继承自己实现的类(一般多重继承)。
  • 对象适配器模式
    在这种适配器模式中,适配器容纳一个它包裹的类的实例。在这种情况下,适配器调用被包裹对象。

类的适配器模式

适配器模式_第1张图片

  • 源(Adapee)角色:现在需要适配的接口。
  • 目标(Target)角色:这就是所期待得到的接口(类适配器模式,目标不可以是类)
  • 适配器(Adapter)角色:适配器类是本模式的核心。适配器把源接口转换成目标接口。显然,这一角色不可以是接口,而必须是具体类。

源(Adapee)角色

我们养了一只猫,它会发出叫声

public class Cat {
    public void makeSound(){
        System.out.println("猫猫:喵喵喵。。。。。。。。。。。。。");
    }
}

目标(Target)角色

public interface OurFriend {
    void speak();
}

适配器(Adapter)角色

public class CatFriend extends Cat implements OurFriend{
    @Override
    public void speak() {
        super.makeSound();
    }
}

测试

public class Person {
    public void speakTo(OurFriend friend){
        System.out.println("人:你在干嘛?");
        friend.speak();
    }

    public static void main(String[] args) {
        Person person=new Person();
        OurFriend friend=new CatFriend();
        person.speakTo(friend);
    }
}

适配器模式_第2张图片

增加源(Adapee)角色的后果

如果有一天又养了一只狗

public class Dog {
    public void makeSound(){
        System.out.println("狗:汪汪汪汪。。。。。。。。。");
    }
}

人又和狗成为了朋友

public class DogFriend extends Dog implements  OurFriend{
    @Override
    public void speak() {
        super.makeSound();
    }
}

重新测试聊天

public class Person {
    public void speakTo(OurFriend friend){
        System.out.println("人:你在干嘛?");
        friend.speak();
    }

    public static void main(String[] args) {
        Person person=new Person();
        OurFriend catFriend=new CatFriend();
        OurFriend dogFriend=new DogFriend();
        person.speakTo(dogFriend);
        person.speakTo(catFriend);
    }
}

适配器模式_第3张图片
如果再有其他朋友,还需要增加适配器。是否有办法使其通用呢?

对象适配器模式

我们希望可以有一个可以和各种动物做朋友的办法,而不是每次有了新的动物朋友都需要增加一个适配器。
适配器模式_第4张图片

让源(Adapee)角色的猫和狗实现动物接口

public class Dog implements IAnimal{
    public void makeSound(){
        System.out.println("狗:汪汪汪汪。。。。。。。。。");
    }
}
public class Cat implements IAnimal{
    public void makeSound(){
        System.out.println("猫猫:喵喵喵。。。。。。。。。。。。。");
    }
}

万物拟人适配器(Adaper)角色

public class AnimalFriendAdaper implements OurFriend{
    private IAnimal animal;

    public AnimalFriendAdaper(IAnimal animal){
        this.animal=animal;
    }

    @Override
    public void speak() {
        animal.makeSound();
    }
}

测试

public class Person {
    public void speakTo(OurFriend friend){
        System.out.println("人:你在干嘛?");
        friend.speak();
    }

    public static void main(String[] args) {
        // 一个人
        Person  person = new Person();
        // 一只狗
        IAnimal dog = new Dog();
        // 一只猫
        IAnimal cat = new Cat();
        // 万物拟人
        person.speakTo(new AnimalFriendAdaper(dog));
        person.speakTo(new AnimalFriendAdaper(cat));

    }
}

适配器模式_第5张图片

你可能感兴趣的:(java,后端,适配器模式,java,开发语言)