Home > Java > javaTutorial > Definition and use of adapter pattern

Definition and use of adapter pattern

零下一度
Release: 2017-07-18 09:51:15
Original
1573 people have browsed it

Definition of Adapter Pattern

Adapter pattern: Convert the interface of a class into another interface that the customer wants. The adapter pattern allows classes with incompatible interfaces to work together

Adapter Pattern:Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn't otherwise because of incompatible interface.
Copy after login

The alias of the adapter pattern is the wrapper pattern, which can be used as either a class structural pattern or an object structural pattern. The interface mentioned in the adapter pattern definition refers to a generalized interface, which can represent a method or a collection of methods.

Existing subclass, adapted object
public class Adaptee {public void adapteeMethod(){
        System.out.println("适配方法");
    }
}
Copy after login
Adapter interface
public interface Target {/** * 适配的接口     */void adapteeMethod();/** * 新增接口     */void adapterMethod();
}
Copy after login
Interface implementation
public class Adapter implements Target{private Adaptee adaptee;public Adapter(Adaptee adaptee) {this.adaptee = adaptee;
    }
    @Overridepublic void adapteeMethod() {this.adaptee.adapteeMethod();
    }

    @Overridepublic void adapterMethod() {
        System.out.println("新增接口");
    }
}
Copy after login
Test
public static void main(String[] args) {
    Target target = new Adapter(new Adaptee());
    target.adapteeMethod();
    target.adapterMethod();
}
Copy after login

The orchestration mode contains the following three roles:

1: Target( Target abstract class): The target abstract class defines the interface required by the customer, which can be an abstract class or interface, or a concrete class. In a class adapter, since the C# language does not support multiple inheritance, it can only be an interface.

 2: Adapter (adapter class): It can call another interface and serve as a converter to adapt Adaptee and Target. It is the core of the adapter pattern.

 3: Adaptee (Adapter class): The adapter is the adapted role. It defines an existing interface. This interface needs to be adapted. The adapter class covers the customer's wishes. business methods.


The above is the detailed content of Definition and use of adapter pattern. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template