Java Design Pattern serialization (6)-adapter Pattern
Name: Adapter
Purpose: Convert the interface of a class to another interface that the customer wants. The A d a p t e r mode makes those classes that cannot work together due to interface incompatibility work together.
Applicability:
You want to use an existing class, and its interface does not meet your needs.
You want to create a reusable class that can work together with other unrelated classes or unforeseen classes (that is, classes whose interfaces may not be compatible.
(Only applicable to object a d a p t e r) You want to use existing subclasses, but it is impossible to subclass each of them to match their interfaces. The Object Adapter can adapt to its parent class interface.
Instance:
1. Build a target interface. You can use this interface but cannot change the source code of this interface. Assume that the interface is locked.
Package adapter_pattern; public interface lock {// target lock public void ordinarylockfunction (); // common lock function}
2. Write an adaptee using the password lock function
Package adapter_pattern; public class tricklock {// adapteepublic void tricklockfunction () {system. Out. println ("password lock can be used to lock the SAFE ");}}
3. Use common locks to build an adapter
package Adapter_Pattern;public class Ordinarylock implements Lock{ //Adapter private Tricklock tricklock; public Ordinarylock(Tricklock tricklock){ this.tricklock = tricklock; } public void ordinarylockFunction() {
tricklock.TricklockFunction(); } }
4. Test class
Package adapter_pattern; public class test {/*** combines a target lock with a password lock function. * @ Param ARGs */public static void main (string [] ARGs) {lock = new ordinarylock (New tricklock (); lock. ordinarylockfunction (); // The lock now has the function of locking the safe }}
5. Thank you for choosing the correct one.