The primary function of the adapter pattern is to convert the interface of one class into another interface that the customer wants. The adapter mode makes it possible for those objects (classes) that would otherwise not work together because of incompatible interfaces to work together.
Uml:
For example, ducks have fly methods and quack methods, turkeys also have fly method and gobble (Cluck) method, if you want the turkey has quack method, can be reused duck, but its call should be cluck. A turkey adapter can be created to enable the Turkey to support the quack method, but inside it or call gobble:
Abstract constructors:
varDuck =function() {};D uck.prototype.fly=function(){ Throw NewError ("The method should be override!");};D Uck.prototype.quack=function(){ Throw NewError ("The method should be override!");};varTurkey =function(){}; Turkey.prototype.fly=function(){ Throw NewError ("The method should be override!");}; Turkey.prototype.gobble=function(){ Throw NewError ("The method should be override!");};
constructor function:
varMallardduck =function() {duck.apply ( This);}; Mallardduck.prototype=NewDuck (); MallardDuck.prototype.fly=function() {Console.log ("It can fly a long way!");}; MallardDuck.prototype.quack=function() {Console.log ("Quack!");};varWildturkey =function() {turkey.apply ( This);}; Wildturkey.prototype=NewTurkey (); WildTurkey.prototype.fly=function() {Console.log ("It can fly a short way!");}; WildTurkey.prototype.gobble=function() {Console.log ("Gobble!");};
Create a turkey adapter:
varTurkeyadapter =function(Oturkey) {duck.apply ( This); This. Oturkey =Oturkey;}; Turkeyadapter.prototype=NewDuck (); TurkeyAdapter.prototype.quack=function(){ This. oturkey.gobble ();}; TurkeyAdapter.prototype.fly=function(){ varNfly = 0; varNlenfly = 5; for(; nfly < nlenfly; nfly++;){ This. Oturkey.fly (); }};
This constructor receives an instance of a turkey, the prototype of this adapter is duck, and then overrides the Duck quack method, invokes the gobble of the turkey instance inside it, and overrides the Fly method, invoking:
var New Mallardduck (); var New Wildturkey (); var New Turkeyadapter (Owildturkey); Omallardduck.fly (); Omallardduck.quack (); Owildturkey.fly (); Owildturkey.gobble () ; Oturkeyadapter.fly (); Oturkeyadapter.quack ();
Usage scenarios for Adapter mode:
1. Want to use an existing object, but its methods or properties do not meet the requirements
2. Want to create a reusable object that can work with other unrelated objects
3. You want to use an object that already exists, but you cannot prototype each one to match its interface. The object adapter can adapt its parent object interface method or property.
JavaScript design mode-Adapter mode