Transforms the interface of one class into another interface that the customer wants. Those classes that would otherwise not work together because of incompatible interfaces can work together.
Scenario: You want to reuse some existing classes, but the interfaces are inconsistent with the reuse environment requirements.
Pattern feature: Transforms the interface of a class into another interface that the customer wants.
Classification: Class adapters (through multiple inheritance), object adapters.
To illustrate by example, here's how a user can use a class using an adapter
Class Target:def request (): print "common request." Class Adaptee (Target): def specificrequest (self): print "specific request." Class Adapter (Target): def __init__ (Self,ada): self.adaptee = Ada def Request (self): Self.adaptee.SpecificRequest () if __name__ = = "__main__": Adaptee = adaptee () adapter = adapter (adaptee) adapter. Request ()
Class Diagram:
Instance:
Let's look at a simple adapter example
#encoding =utf-8 # #by Panda #适配器模式 def printinfo (info): Print Unicode (info, ' utf-8 '). Encode (' GBK ') #球员类 class Player () : Name = "Def __init__ (self,name): self.name = name def Attack (self,name): Pass def Defense (self): Pass #前锋 class Forwards (Player): def __init__ (self,name): player.__init__ (Self,name) def Attack (self): Printinfo ("Striker%s Offense "% self.name" def Defense (self,name): Printinfo ("Striker%s defensive"% Self.name) #中锋 (target Class) class Center (Player): Def __init __ (Self,name): player.__init__ (Self,name) def Attack (self): printinfo ("Center%s offense"% self.name) def Defense (self): Printinfo ("center%s defensive"% self.name) #后卫 class Guards (Player): def __init__ (self,name): player.__init__ (self,name) d EF Attack (self): Printinfo ("defender%s offense"% self.name) def Defense (self): Printinfo ("defender%s Defense"% self.name) #外籍中锋 (to be adapted class) #中锋 class Foreigncenter (Player): name = "Def __init__ (self,name): player.__init__ (Self,name) def foreignattack (s ELF): Printinfo ("Foreign Center%S offense "% self.name" def foreigndefense (self): printinfo ("Foreign center%s defensive"% self.name) #翻译 (Adaptive Class) class Translator (Player): Foreigncenter = None def __init__ (self,name): Self.foreigncenter = Foreigncenter (name) def Attack (self): self.for Eigncenter.foreignattack () def Defense (self): Self.foreignCenter.ForeignDefense () def clientui (): b = Forwards (' Buddy m = Guards (' mcgrady ') ym = Translator (' Yao ') b.attack () m.defense () ym. Attack () ym. Defense () return if __name__ = = ' __main__ ': Clientui ();