Design Patterns (12) - Detailed Explanation of Adapter Patterns (Easy to Understand)

Definition of Adapter Pattern

In computer programming, the adapter pattern (sometimes called wrapper style or wrapper) adapts a class's interface to what the user expects. An adaptation allows classes that would normally not work together because of incompatible interfaces to work together, by wrapping the class's own interface in an existing class.

There are two types of adapter modes:

Object Adapter Pattern

  • In this adapter pattern, the adapter holds an instance of the class it wraps. In this case, the adapter calls the physics entity of the wrapped object.

class adapter pattern

  •  -- In this adapter mode, the adapter inherits from the implemented class.

Model:

 

  • Target: The target role, which defines the role that converts other classes into our expected roles

  • Adaptee: The initial role, that is, our original class and interface objects, such as "A->B", where A is the initial role, which has always existed

  • Adapter: The adapter role, which is our focus today, the adapter needs to be newly created, and the initial role is converted into the target role through inheritance and other methods.

Code demo (class adapter pattern):

1. AbstractTarget: abstract target role

public interface AbstractTarget {
   //Abstract target role method
   public void target () ;
}

2. Specific target roles

public class Target implements AbstractTarget {
   @Override
   public void target() {
       Log.d("qzs","实现目标方法");
   }
}

3.初始角色Adaptee:

public class Adaptee {
   //初始的方法
   public void adaptee(){
       Log.d("qzs","初始的逻辑");
   }
}

4.适配器角色:

public class Adapter extends Adaptee implements AbstractTarget {
   @Override
   public void target() {
      adaptee();
   }
}

5.调用

AbstractTarget tr=new Adapter();      
  tr.target();

实例说明

例如,我手中有Android数据线和iphone手机,我想用安卓数据线给iphone手机充电。此时:

  • 初始角色:Android数据线

  • 目标角色:iphone手机

  • 适配器:数据线转换器

代码演示:

1.Android数据线:

 

public class AndroidLine {
   public  void  charge(){
       Log.d("qzs","Android数据线给Android手机充电");
   }
}

 

2.目标角色:

public interface AbstractIphone {
   public  void  target();
}

 

3.数据线转换器

public class PhoneLineAdapter extends AndroidLine implements  AbstractIphone {
   @Override
   public void target() {
       super.charge();
       Log.d("qzs","但是我可以通过数据线转换器来给iphone手机充电");
   }
}

 

4.调用

AbstractIphone tr1=new PhoneLineAdapter();
       tr1.target();

运行:

适配器模式的优点及其他

1.优点

  • 灵活性好

  • 通过适配器可以让两个没有关系的类一起运行

  • 增加了类的通透性

2.注意:

当初始角色的接口和实现类为多个时,我们在写适配器不能用继承的方式。可以通过在适配器中构造函数的方法来传递对象从而实现数据处理,也就是对象适配器模式。

文章参考了网上信息以及《设计模式之禅》

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326008739&siteId=291194637