Design Pattern (2) Adapter Pattern

Source: Internet
Author: User

I learned the Adapter mode today. An adapter helps two incompatible interfaces to work together. this is the real world definition for an adapter. adapter design pattern is used when you want two different classes with incompatible interfaces to work together. the name says it all. interfaces may be incompatible but the inner functionality shocould suit the need. the Adapter pattern allows otherwise incompatible classes To work together by converting the interface of one class into an interface expected by the clients. the following example shows two types of Play and Walk public class Play {public void playPhone () {System. out. println ("play iphone") ;}} public class Walk {public void walk () {System. out. println ("I walk on the street") ;}} now you need an adapter that allows a person to walk and play with a cell phone, so that the adapter inherits one of the classes, then, the other class is used as a member variable of the adapter class. Public class secure adapter {private Play play Play; public secure adapter (play Play play) {this. play = play;} public void play () {return play. playPhone () ;}} can also use multiple inheritance, but Java does not have multiple inheritance, and can only be implemented through interfaces. Set two interfaces to implement two classes. Public interface IPlay {public void playPhone ();} public interface IWalk {public void walk ();} public class Play implements IPlay {@ Overridepublic void playPhone () {System. out. println ("play iphone") ;}} public class Walk implements IWalk {@ Overridepublic void walk () {System. out. println ("I walk on the street") ;}} then let the Adapter implement two interfaces, and let the two class objects as the member variables of the Adapter. Public class Adapter implements IWalk, IPlay {private Play play Play; private Walk walk; public Adapter (play Play play, Walk) {this. play = play; this. walk = walk;} public void play () {return play. playPhone ();} public void walk () {return walk. walk ();}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.