SlideShare a Scribd company logo
The
                                  Adapter
                                  Pattern


Design Patterns In Java                                                          Bob Tarr




                               The Adapter Pattern

l    Intent
      é    Convert the interface of a class into another interface clients expect.
           Adapter lets classes work together that couldn't otherwise because of
           incompatible interfaces.
l    Also Known As
      é    Wrapper
l    Motivation
      é    Sometimes a toolkit or class library can not be used because its interface is
           incompatible with the interface required by an application
      é    We can not change the library interface, since we may not have its source
           code
      é    Even if we did have the source code, we probably should not change the
           library for each domain-specific application


Design Patterns In Java
                                     The Adapter Pattern                             Bob Tarr
                                              2




                                                                                                1
The Adapter Pattern

l    Motivation
      é    Example:




Design Patterns In Java
                                     The Adapter Pattern                          Bob Tarr
                                             3




                               The Adapter Pattern

l    Structure
      é    A class adapter uses multiple inheritance to adapt one interface to another:




Design Patterns In Java
                                     The Adapter Pattern                          Bob Tarr
                                             4




                                                                                             2
The Adapter Pattern

l    Structure
      é    An object adapter relies on object composition:




Design Patterns In Java
                                        The Adapter Pattern                              Bob Tarr
                                                  5




                                  The Adapter Pattern

l    Applicability
      Use the Adapter pattern when
      é You want to use an existing class, and its interface does not match the one
        you need
      é You want to create a reusable class that cooperates with unrelated classes
        with incompatible interfaces
l    Implementation Issues
      é    How much adapting should be done?
             Ý   Simple interface conversion that just changes operation names and order of
                 arguments
             Ý   Totally different set of operations
      é    Does the adapter provide two-way transparency?
             Ý   A two-way adapter supports both the Target and the Adaptee interface. It
                 allows an adapted object (Adapter) to appear as an Adaptee object or a Target
                 object

Design Patterns In Java
                                        The Adapter Pattern                              Bob Tarr
                                                  6




                                                                                                    3
Adapter Pattern Example 1

l    The classic round pegs and square pegs!
l    Here's the SquarePeg class:
     /**
       * The SquarePeg class.
       * This is the Target class.
       */
     public class SquarePeg {
        public void insert(String str) {
          System.out.println("SquarePeg insert(): " + str);
        }
     }




Design Patterns In Java
                                  The Adapter Pattern                Bob Tarr
                                          7




                      Adapter Pattern Example 1 (Continued)

l    And the RoundPeg class:
     /**
       * The RoundPeg class.
       * This is the Adaptee class.
       */
     public class RoundPeg {
        public void insertIntoHole(String msg) {
          System.out.println("RoundPeg insertIntoHole(): " + msg);
        }
     }


l    If a client only understands the SquarePeg interface for inserting
     pegs using the insert() method, how can it insert round pegs? A
     peg adapter!

Design Patterns In Java
                                  The Adapter Pattern                Bob Tarr
                                          8




                                                                                4
Adapter Pattern Example 1 (Continued)

l    Here is the PegAdapter class:
        /**
         * The PegAdapter class.
         * This is the Adapter class.
         * It adapts a RoundPeg to a SquarePeg.
         * Its interface is that of a SquarePeg.
         */
        public class PegAdapter extends SquarePeg {
          private RoundPeg roundPeg;

            public PegAdapter(RoundPeg peg)     {this.roundPeg = peg;}

            public void insert(String str)     {roundPeg.insertIntoHole(str);}

        }



Design Patterns In Java
                                  The Adapter Pattern                     Bob Tarr
                                          9




                      Adapter Pattern Example 1 (Continued)


    l       Typical client program:
            // Test program for Pegs.
            public class TestPegs {
              public static void main(String args[])     {

                // Create some pegs.
                RoundPeg roundPeg = new RoundPeg();
                SquarePeg squarePeg = new SquarePeg();

                // Do an insert using the square peg.
                squarePeg.insert("Inserting square peg...");




Design Patterns In Java
                                  The Adapter Pattern                     Bob Tarr
                                          10




                                                                                     5
Adapter Pattern Example 1 (Continued)


             // Now we'd like to do an insert using the round peg.
             // But this client only understands the insert()
             // method of pegs, not a insertIntoHole() method.
             // The solution: create an adapter that adapts
             // a square peg to a round peg!
             PegAdapter adapter = new PegAdapter(roundPeg);
             adapter.insert("Inserting round peg...");
         }

     }


l    Client program output:
     SquarePeg insert(): Inserting square peg...
     RoundPeg insertIntoHole(): Inserting round peg...



Design Patterns In Java
                                  The Adapter Pattern                Bob Tarr
                                          11




                           Adapter Pattern Example 2

l    Notice in Example 1 that the PegAdapter adapts a RoundPeg to a
     SquarePeg. The interface for PegAdapter is that of a SquarePeg.
l    What if we want to have an adapter that acts as a SquarePeg or a
     RoundPeg? Such an adapter is called a two-way adapter.
l    One way to implement two-way adapters is to use multiple
     inheritance, but we can't do this in Java
l    But we can have our adapter class implement two different Java
     interfaces!




Design Patterns In Java
                                  The Adapter Pattern                Bob Tarr
                                          12




                                                                                6
Adapter Pattern Example 2 (Continued)

l    Here are the interfaces for round and square pegs:
     /**
       *The IRoundPeg interface.
       */
     public interface IRoundPeg {
        public void insertIntoHole(String msg);
     }



     /**
       *The ISquarePeg interface.
       */
     public interface ISquarePeg {
        public void insert(String str);
     }



Design Patterns In Java
                                  The Adapter Pattern               Bob Tarr
                                          13




                      Adapter Pattern Example 2 (Continued)

l    Here are the new RoundPeg and SquarePeg classes. These are
     essentially the same as before except they now implement the
     appropriate interface.
     // The RoundPeg class.
     public class RoundPeg implements IRoundPeg {
       public void insertIntoHole(String msg) {
         System.out.println("RoundPeg insertIntoHole(): " + msg);
       }
     }

     // The SquarePeg class.
     public class SquarePeg implements ISquarePeg {
       public void insert(String str) {
         System.out.println("SquarePeg insert(): " + str);
       }
     }

Design Patterns In Java
                                  The Adapter Pattern               Bob Tarr
                                          14




                                                                               7
Adapter Pattern Example 2 (Continued)

l    And here is the new PegAdapter:
     /**
      * The PegAdapter class.
      * This is the two-way adapter class.
      */
     public class PegAdapter implements ISquarePeg, IRoundPeg {
       private RoundPeg roundPeg;
       private SquarePeg squarePeg;

         public PegAdapter(RoundPeg peg) {this.roundPeg = peg;}

         public PegAdapter(SquarePeg peg) {this.squarePeg = peg;}

         public void insert(String str) {roundPeg.insertIntoHole(str);}

         public void insertIntoHole(String msg){squarePeg.insert(msg);}
     }
Design Patterns In Java
                                  The Adapter Pattern               Bob Tarr
                                          15




                      Adapter Pattern Example 2 (Continued)

l    A client that uses the two-way adapter:
     // Test program for Pegs.
     public class TestPegs {
       public static void main(String args[]) {
         // Create some pegs.
         RoundPeg roundPeg = new RoundPeg();
         SquarePeg squarePeg = new SquarePeg();

            // Do an insert using the square peg.
            squarePeg.insert("Inserting square peg...");

            // Create a two-way adapter and do an insert with it.
            ISquarePeg roundToSquare = new PegAdapter(roundPeg);
            roundToSquare.insert("Inserting round peg...");




Design Patterns In Java
                                  The Adapter Pattern               Bob Tarr
                                          16




                                                                               8
Adapter Pattern Example 2 (Continued)

             // Do an insert using the round peg.
             roundPeg.insertIntoHole("Inserting round peg...");

             // Create a two-way adapter and do an insert with it.
             IRoundPeg squareToRound = new PegAdapter(squarePeg);
             squareToRound.insertIntoHole("Inserting square peg...");
         }
     }



l    Client program output:
     SquarePeg insert(): Inserting square         peg...
     RoundPeg insertIntoHole(): Inserting         round peg...
     RoundPeg insertIntoHole(): Inserting         round peg...
     SquarePeg insert(): Inserting square         peg...



Design Patterns In Java
                                  The Adapter Pattern                   Bob Tarr
                                          17




                           Adapter Pattern Example 3

l    This example comes from Roger Whitney, San Diego State
     University
l    Situation: A Java class library exists for creating CGI web server
     programs. One class in the library is the CGIVariables class
     which stores all CGI environment variables in a hash table and
     allows access to them via a get(String evName) method. Many
     Java CGI programs have been written using this library. The
     latest version of the web server supports servlets, which provide
     functionality similar to CGI programs, but are considerably more
     efficient. The servlet library has an HttpServletRequest class
     which has a getX() method for each CGI environment variable.
     We want to use servlets. Should we rewrite all of our existing
     Java CGI programs??

Design Patterns In Java
                                  The Adapter Pattern                   Bob Tarr
                                          18




                                                                                   9
Adapter Pattern Example 3

l    Solution : Well, we'll have to do some rewriting, but let's attempt
     to minimize things. We can design a CGIAdapter class which has
     the same interface (a get() method) as the original CGIVariables
     class, but which puts a wrapper around the HttpServletRequest
     class. Our CGI programs must now use this CGIAdapter class
     rather than the original CGIVariables class, but the form of the
     get() method invocations need not change.




Design Patterns In Java
                                  The Adapter Pattern               Bob Tarr
                                          19




                      Adapter Pattern Example 3 (Continued)

l    Here's a snippet of the CGIAdapter class:
     public class CGIAdapter {
       Hashtable CGIVariables = new Hashtable(20);

         public CGIAdapter(HttpServletRequest CGIEnvironment) {
           CGIVariables.put("AUTH_TYPE", CGIEnvironment.getAuthType());
           CGIVariables.put("REMOTE_USER",
                            CGIEnvironment.getRemoteUser());
           etc.
         }

         public Object get(Object key) {return CGIvariables.get(key);}

     }

l    Note that in this example, the Adapter class (CGIAdapter) itself
     constructs the Adaptee class (CGIVariables)
Design Patterns In Java
                                  The Adapter Pattern               Bob Tarr
                                          20




                                                                               10
Adapter Pattern Example 4

l    Consider a utility class that has a copy() method which can make
     a copy of an vector excluding those objects that meet a certain
     criteria. To accomplish this the method assumes that all objects
     in the vector implement the Copyable interface providing the
     isCopyable() method to determine if the object should be copied
     or not.
                                                      Copyable Interface
               VectorUtilities
                                                    isCopyable()




                                                         BankAccount




Design Patterns In Java
                                       The Adapter Pattern                 Bob Tarr
                                               21




                      Adapter Pattern Example 4 (Continued)

l    Here’s the Copyable interface:
     public interface Copyable {
       public boolean isCopyable();
     }

l    And here’s the copy() method of the VectorUtilities class:
     public static Vector copy(Vector vin) {
       Vector vout = new Vector();
       Enumeration e = vin.elements();
       while (e.hasMoreElements()) {
         Copyable c = (Copyable) e.nextElement();
         if (c.isCopyable())
           vout.addElemet(c);
       }
       return vout;
     }

Design Patterns In Java
                                       The Adapter Pattern                 Bob Tarr
                                               22




                                                                                      11
Adapter Pattern Example 4 (Continued)

l    But what if we have a class, say the Document class, that does not
     implement the Copyable interface. We want to be able perform a
     selective copy of a vector of Document objects, but we do not
     want to modify the Document class at all. Sounds like a job for
     (TA-DA) an adapter!
l    To make things simple, let’s assume that the Document class has
     a nice isValid() method we can invoke to determine whether or
     not it should be copied




Design Patterns In Java
                                   The Adapter Pattern               Bob Tarr
                                              23




                      Adapter Pattern Example 4 (Continued)

l    Here’s our new class diagram:

                                 Copyable Interface
        VectorUtilities
                               isCopyable()



                                                          Document
                                 DocumentAdapter
                                                         isValid()




Design Patterns In Java
                                   The Adapter Pattern               Bob Tarr
                                              24




                                                                                12
Adapter Pattern Example 4 (Continued)

l    And here is our DocumentAdapter class:
     public class DocumentAdapter implements Copyable {

         private Document d;

         public DocumentAdapter(Document d) {
           document = d;
         }

         public boolean isCopyable() {
           return d.isValid();
         }

     }




Design Patterns In Java
                                  The Adapter Pattern         Bob Tarr
                                          25




                           Adapter Pattern Example 5

l    Do you see any Adapter pattern here?
     public class ButtonDemo {

         public ButtonDemo() {
           Button button = new Button("Press me");
           button.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                doOperation();
             }
           });
         }
         public void doOperation() { whatever }

     }




Design Patterns In Java
                                  The Adapter Pattern         Bob Tarr
                                          26




                                                                         13
Adapter Pattern Example 5 (Continued)

l    Button objects expect to be able to invoke the actionPerformed()
     method on their associated ActionListener objects. But the
     ButtonDemo class does not have this method! It really wants the
     button to invoke its doOperation() method. The anonymous inner
     class we instantiated acts as an adapter object, adapting
     ButtonDemo to ActionListener!




Design Patterns In Java
                                  The Adapter Pattern           Bob Tarr
                                          27




                                                                           14

More Related Content

What's hot (20)

PPT
Design Patterns (Examples in .NET)
Aniruddha Chakrabarti
 
PPT
Understanding Annotations in Java
Ecommerce Solution Provider SysIQ
 
PDF
Irving iOS Jumpstart Meetup - Objective-C Session 1b
irving-ios-jumpstart
 
PPTX
Type Annotations in Java 8
FinLingua, Inc.
 
PDF
Design Patterns Illustrated
Herman Peeren
 
PDF
You need to extend your models? EMF Facet vs. EMF Profiles
Philip Langer
 
PPTX
Gof design patterns
Srikanth R Vaka
 
PDF
Pocket java
Kumaran K
 
PPS
Jump start to OOP, OOAD, and Design Pattern
Nishith Shukla
 
PPSX
Java annotations
FAROOK Samath
 
PPT
Bartlesville Dot Net User Group Design Patterns
Jason Townsend, MBA
 
PDF
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Institute of Science Tokyo
 
PDF
2013 bookmatter learn_javaforandroiddevelopment
CarlosPineda729332
 
PPT
Oo Design And Patterns
Anil Bapat
 
PPS
Coding Best Practices
mh_azad
 
PDF
Boogie 2011 Hi-Lite
AdaCore
 
PPSX
Object oriented concepts & programming (2620003)
nirajmandaliya
 
PDF
Exception handling
Ravi Kant Sahu
 
ZIP
Introduction to the Java(TM) Advanced Imaging API
white paper
 
PPTX
Android code convention
Siddiq Abu Bakkar
 
Design Patterns (Examples in .NET)
Aniruddha Chakrabarti
 
Understanding Annotations in Java
Ecommerce Solution Provider SysIQ
 
Irving iOS Jumpstart Meetup - Objective-C Session 1b
irving-ios-jumpstart
 
Type Annotations in Java 8
FinLingua, Inc.
 
Design Patterns Illustrated
Herman Peeren
 
You need to extend your models? EMF Facet vs. EMF Profiles
Philip Langer
 
Gof design patterns
Srikanth R Vaka
 
Pocket java
Kumaran K
 
Jump start to OOP, OOAD, and Design Pattern
Nishith Shukla
 
Java annotations
FAROOK Samath
 
Bartlesville Dot Net User Group Design Patterns
Jason Townsend, MBA
 
Generating Assertion Code from OCL: A Transformational Approach Based on Simi...
Institute of Science Tokyo
 
2013 bookmatter learn_javaforandroiddevelopment
CarlosPineda729332
 
Oo Design And Patterns
Anil Bapat
 
Coding Best Practices
mh_azad
 
Boogie 2011 Hi-Lite
AdaCore
 
Object oriented concepts & programming (2620003)
nirajmandaliya
 
Exception handling
Ravi Kant Sahu
 
Introduction to the Java(TM) Advanced Imaging API
white paper
 
Android code convention
Siddiq Abu Bakkar
 

Viewers also liked (10)

PDF
Webinar on Design Patterns titled 'Dive into Design Patterns'
Edureka!
 
PPTX
Implementing the Adapter Design Pattern
ProdigyView
 
PDF
android design pattern
Lucas Xu
 
PPT
Structural patterns
Himanshu
 
PPTX
презентацыя
kuzenka
 
PDF
The Adapter Pattern in PHP
Darren Craig
 
PPT
Adapter pattern
Shakil Ahmed
 
PPTX
Adapter Pattern
Ted Liang
 
PPTX
Structural Design pattern - Adapter
Manoj Kumar
 
PPT
Design patterns ppt
Aman Jain
 
Webinar on Design Patterns titled 'Dive into Design Patterns'
Edureka!
 
Implementing the Adapter Design Pattern
ProdigyView
 
android design pattern
Lucas Xu
 
Structural patterns
Himanshu
 
презентацыя
kuzenka
 
The Adapter Pattern in PHP
Darren Craig
 
Adapter pattern
Shakil Ahmed
 
Adapter Pattern
Ted Liang
 
Structural Design pattern - Adapter
Manoj Kumar
 
Design patterns ppt
Aman Jain
 
Ad

Similar to Adapter 2pp (20)

ZIP
Adapter Design Pattern
guy_davis
 
PDF
Adapter Pattern Abhijit Hiremagalur 200603
melbournepatterns
 
PPTX
Presentation on adapter pattern
Tanim Ahmed
 
PPTX
Adapter design pattern
manik_114
 
PDF
software Structural design pattern Adapter
mdimberu
 
PDF
Software and architecture design pattern
sanjanakorawar
 
PPTX
Design Patern::Adaptor pattern
Jyaasa Technologies
 
PPT
Design patterns structuralpatterns(theadapterpattern)
APU
 
PPTX
UNIT IV DESIGN PATTERNS.pptx
anguraju1
 
PPTX
Design patterns
Alok Guha
 
PPT
Itp design patterns - 2003
Shibu S R
 
KEY
Design Patterns Course
Ahmed Soliman
 
PDF
Design patterns elements of reusable object-oriented programming
hernan rodriguez arzate
 
PDF
Design Patterns
adil raja
 
PDF
Design patters java_meetup_slideshare [compatibility mode]
Dimitris Dranidis
 
PPT
Design pattern in android
Jay Kumarr
 
PPTX
L03 Design Patterns
Ólafur Andri Ragnarsson
 
PPTX
L05 Design Patterns
Ólafur Andri Ragnarsson
 
PDF
Design Patterns - GOF
Fanus van Straten
 
Adapter Design Pattern
guy_davis
 
Adapter Pattern Abhijit Hiremagalur 200603
melbournepatterns
 
Presentation on adapter pattern
Tanim Ahmed
 
Adapter design pattern
manik_114
 
software Structural design pattern Adapter
mdimberu
 
Software and architecture design pattern
sanjanakorawar
 
Design Patern::Adaptor pattern
Jyaasa Technologies
 
Design patterns structuralpatterns(theadapterpattern)
APU
 
UNIT IV DESIGN PATTERNS.pptx
anguraju1
 
Design patterns
Alok Guha
 
Itp design patterns - 2003
Shibu S R
 
Design Patterns Course
Ahmed Soliman
 
Design patterns elements of reusable object-oriented programming
hernan rodriguez arzate
 
Design Patterns
adil raja
 
Design patters java_meetup_slideshare [compatibility mode]
Dimitris Dranidis
 
Design pattern in android
Jay Kumarr
 
L03 Design Patterns
Ólafur Andri Ragnarsson
 
L05 Design Patterns
Ólafur Andri Ragnarsson
 
Design Patterns - GOF
Fanus van Straten
 
Ad

Recently uploaded (20)

PDF
Partnering Locally, Delivering Globally with Precision
Newman Leech
 
PDF
241108_Assagaon Mds fsadssd sterplan.pdf
ishamenezes2
 
PDF
AfricaMineralsManufacturingPlantCitiesDevelopmentClub.pdf
OsaJOkundayeODMDFAAO
 
PDF
Top 20 Curated List of Luxury Penthouses in Phnom Penh KH
Hoem Seiha
 
PDF
FHA Home Inspection with eAuditor Audits & Inspections
eAuditor Audits & Inspections
 
PDF
Find Your Ideal Workspace in Noida with SVAM Work
svamwork
 
PDF
Experience Affordable Luxury Living at Spacia Madhyamgram – North Kolkata’s P...
spaciamadhyamgram
 
PDF
Promenade Peak Condo at Zion Road, Singapore.pdf
Lance Kuan
 
PDF
Alberta Inc. Fueling Growth in Canada's Economic Core.pdf
cashcars4info
 
PPTX
What Makes Brick & Bolt Different from Local Contractors .pptx
BrickAndBolt
 
PDF
AKZIRVE TOPKAPI29 Dijital Catalog - Listing Turkey
Listing Turkey
 
PDF
Springleaf Residence, a new condominium Development in Singapore.pdf
Lance Kuan
 
PDF
Boosting Real Estate Portfolio Performance.pdf
Leni Co
 
PPTX
Types_of_Villages_in_Ghana man villages i
sheilababy2014
 
PDF
DLF West Park Mumbai - Elegant Living in Andheri West
DLF The Dahlias
 
PDF
Brian McDaniel’s Blueprint for Personalized Property Success
Brian McDaniel
 
PDF
Gated Community Villas for Sales in Hyderabad.
manjulaforestnation
 
PDF
Top Reasons to Enroll in Multifamily Investing Training Today
multifamilystrategyu
 
PDF
PVC Wall Coverings for Dog Kennels – Durable, Low Maintenance & Easy to Clean
Duramax PVC Wall Panels
 
PPTX
Hamad Al Wazzan Redefining the American Real Estate Landscape.pptx
Hamad Al Wazzan
 
Partnering Locally, Delivering Globally with Precision
Newman Leech
 
241108_Assagaon Mds fsadssd sterplan.pdf
ishamenezes2
 
AfricaMineralsManufacturingPlantCitiesDevelopmentClub.pdf
OsaJOkundayeODMDFAAO
 
Top 20 Curated List of Luxury Penthouses in Phnom Penh KH
Hoem Seiha
 
FHA Home Inspection with eAuditor Audits & Inspections
eAuditor Audits & Inspections
 
Find Your Ideal Workspace in Noida with SVAM Work
svamwork
 
Experience Affordable Luxury Living at Spacia Madhyamgram – North Kolkata’s P...
spaciamadhyamgram
 
Promenade Peak Condo at Zion Road, Singapore.pdf
Lance Kuan
 
Alberta Inc. Fueling Growth in Canada's Economic Core.pdf
cashcars4info
 
What Makes Brick & Bolt Different from Local Contractors .pptx
BrickAndBolt
 
AKZIRVE TOPKAPI29 Dijital Catalog - Listing Turkey
Listing Turkey
 
Springleaf Residence, a new condominium Development in Singapore.pdf
Lance Kuan
 
Boosting Real Estate Portfolio Performance.pdf
Leni Co
 
Types_of_Villages_in_Ghana man villages i
sheilababy2014
 
DLF West Park Mumbai - Elegant Living in Andheri West
DLF The Dahlias
 
Brian McDaniel’s Blueprint for Personalized Property Success
Brian McDaniel
 
Gated Community Villas for Sales in Hyderabad.
manjulaforestnation
 
Top Reasons to Enroll in Multifamily Investing Training Today
multifamilystrategyu
 
PVC Wall Coverings for Dog Kennels – Durable, Low Maintenance & Easy to Clean
Duramax PVC Wall Panels
 
Hamad Al Wazzan Redefining the American Real Estate Landscape.pptx
Hamad Al Wazzan
 

Adapter 2pp

  • 1. The Adapter Pattern Design Patterns In Java Bob Tarr The Adapter Pattern l Intent é Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. l Also Known As é Wrapper l Motivation é Sometimes a toolkit or class library can not be used because its interface is incompatible with the interface required by an application é We can not change the library interface, since we may not have its source code é Even if we did have the source code, we probably should not change the library for each domain-specific application Design Patterns In Java The Adapter Pattern Bob Tarr 2 1
  • 2. The Adapter Pattern l Motivation é Example: Design Patterns In Java The Adapter Pattern Bob Tarr 3 The Adapter Pattern l Structure é A class adapter uses multiple inheritance to adapt one interface to another: Design Patterns In Java The Adapter Pattern Bob Tarr 4 2
  • 3. The Adapter Pattern l Structure é An object adapter relies on object composition: Design Patterns In Java The Adapter Pattern Bob Tarr 5 The Adapter Pattern l Applicability Use the Adapter pattern when é You want to use an existing class, and its interface does not match the one you need é You want to create a reusable class that cooperates with unrelated classes with incompatible interfaces l Implementation Issues é How much adapting should be done? Ý Simple interface conversion that just changes operation names and order of arguments Ý Totally different set of operations é Does the adapter provide two-way transparency? Ý A two-way adapter supports both the Target and the Adaptee interface. It allows an adapted object (Adapter) to appear as an Adaptee object or a Target object Design Patterns In Java The Adapter Pattern Bob Tarr 6 3
  • 4. Adapter Pattern Example 1 l The classic round pegs and square pegs! l Here's the SquarePeg class: /** * The SquarePeg class. * This is the Target class. */ public class SquarePeg { public void insert(String str) { System.out.println("SquarePeg insert(): " + str); } } Design Patterns In Java The Adapter Pattern Bob Tarr 7 Adapter Pattern Example 1 (Continued) l And the RoundPeg class: /** * The RoundPeg class. * This is the Adaptee class. */ public class RoundPeg { public void insertIntoHole(String msg) { System.out.println("RoundPeg insertIntoHole(): " + msg); } } l If a client only understands the SquarePeg interface for inserting pegs using the insert() method, how can it insert round pegs? A peg adapter! Design Patterns In Java The Adapter Pattern Bob Tarr 8 4
  • 5. Adapter Pattern Example 1 (Continued) l Here is the PegAdapter class: /** * The PegAdapter class. * This is the Adapter class. * It adapts a RoundPeg to a SquarePeg. * Its interface is that of a SquarePeg. */ public class PegAdapter extends SquarePeg { private RoundPeg roundPeg; public PegAdapter(RoundPeg peg) {this.roundPeg = peg;} public void insert(String str) {roundPeg.insertIntoHole(str);} } Design Patterns In Java The Adapter Pattern Bob Tarr 9 Adapter Pattern Example 1 (Continued) l Typical client program: // Test program for Pegs. public class TestPegs { public static void main(String args[]) { // Create some pegs. RoundPeg roundPeg = new RoundPeg(); SquarePeg squarePeg = new SquarePeg(); // Do an insert using the square peg. squarePeg.insert("Inserting square peg..."); Design Patterns In Java The Adapter Pattern Bob Tarr 10 5
  • 6. Adapter Pattern Example 1 (Continued) // Now we'd like to do an insert using the round peg. // But this client only understands the insert() // method of pegs, not a insertIntoHole() method. // The solution: create an adapter that adapts // a square peg to a round peg! PegAdapter adapter = new PegAdapter(roundPeg); adapter.insert("Inserting round peg..."); } } l Client program output: SquarePeg insert(): Inserting square peg... RoundPeg insertIntoHole(): Inserting round peg... Design Patterns In Java The Adapter Pattern Bob Tarr 11 Adapter Pattern Example 2 l Notice in Example 1 that the PegAdapter adapts a RoundPeg to a SquarePeg. The interface for PegAdapter is that of a SquarePeg. l What if we want to have an adapter that acts as a SquarePeg or a RoundPeg? Such an adapter is called a two-way adapter. l One way to implement two-way adapters is to use multiple inheritance, but we can't do this in Java l But we can have our adapter class implement two different Java interfaces! Design Patterns In Java The Adapter Pattern Bob Tarr 12 6
  • 7. Adapter Pattern Example 2 (Continued) l Here are the interfaces for round and square pegs: /** *The IRoundPeg interface. */ public interface IRoundPeg { public void insertIntoHole(String msg); } /** *The ISquarePeg interface. */ public interface ISquarePeg { public void insert(String str); } Design Patterns In Java The Adapter Pattern Bob Tarr 13 Adapter Pattern Example 2 (Continued) l Here are the new RoundPeg and SquarePeg classes. These are essentially the same as before except they now implement the appropriate interface. // The RoundPeg class. public class RoundPeg implements IRoundPeg { public void insertIntoHole(String msg) { System.out.println("RoundPeg insertIntoHole(): " + msg); } } // The SquarePeg class. public class SquarePeg implements ISquarePeg { public void insert(String str) { System.out.println("SquarePeg insert(): " + str); } } Design Patterns In Java The Adapter Pattern Bob Tarr 14 7
  • 8. Adapter Pattern Example 2 (Continued) l And here is the new PegAdapter: /** * The PegAdapter class. * This is the two-way adapter class. */ public class PegAdapter implements ISquarePeg, IRoundPeg { private RoundPeg roundPeg; private SquarePeg squarePeg; public PegAdapter(RoundPeg peg) {this.roundPeg = peg;} public PegAdapter(SquarePeg peg) {this.squarePeg = peg;} public void insert(String str) {roundPeg.insertIntoHole(str);} public void insertIntoHole(String msg){squarePeg.insert(msg);} } Design Patterns In Java The Adapter Pattern Bob Tarr 15 Adapter Pattern Example 2 (Continued) l A client that uses the two-way adapter: // Test program for Pegs. public class TestPegs { public static void main(String args[]) { // Create some pegs. RoundPeg roundPeg = new RoundPeg(); SquarePeg squarePeg = new SquarePeg(); // Do an insert using the square peg. squarePeg.insert("Inserting square peg..."); // Create a two-way adapter and do an insert with it. ISquarePeg roundToSquare = new PegAdapter(roundPeg); roundToSquare.insert("Inserting round peg..."); Design Patterns In Java The Adapter Pattern Bob Tarr 16 8
  • 9. Adapter Pattern Example 2 (Continued) // Do an insert using the round peg. roundPeg.insertIntoHole("Inserting round peg..."); // Create a two-way adapter and do an insert with it. IRoundPeg squareToRound = new PegAdapter(squarePeg); squareToRound.insertIntoHole("Inserting square peg..."); } } l Client program output: SquarePeg insert(): Inserting square peg... RoundPeg insertIntoHole(): Inserting round peg... RoundPeg insertIntoHole(): Inserting round peg... SquarePeg insert(): Inserting square peg... Design Patterns In Java The Adapter Pattern Bob Tarr 17 Adapter Pattern Example 3 l This example comes from Roger Whitney, San Diego State University l Situation: A Java class library exists for creating CGI web server programs. One class in the library is the CGIVariables class which stores all CGI environment variables in a hash table and allows access to them via a get(String evName) method. Many Java CGI programs have been written using this library. The latest version of the web server supports servlets, which provide functionality similar to CGI programs, but are considerably more efficient. The servlet library has an HttpServletRequest class which has a getX() method for each CGI environment variable. We want to use servlets. Should we rewrite all of our existing Java CGI programs?? Design Patterns In Java The Adapter Pattern Bob Tarr 18 9
  • 10. Adapter Pattern Example 3 l Solution : Well, we'll have to do some rewriting, but let's attempt to minimize things. We can design a CGIAdapter class which has the same interface (a get() method) as the original CGIVariables class, but which puts a wrapper around the HttpServletRequest class. Our CGI programs must now use this CGIAdapter class rather than the original CGIVariables class, but the form of the get() method invocations need not change. Design Patterns In Java The Adapter Pattern Bob Tarr 19 Adapter Pattern Example 3 (Continued) l Here's a snippet of the CGIAdapter class: public class CGIAdapter { Hashtable CGIVariables = new Hashtable(20); public CGIAdapter(HttpServletRequest CGIEnvironment) { CGIVariables.put("AUTH_TYPE", CGIEnvironment.getAuthType()); CGIVariables.put("REMOTE_USER", CGIEnvironment.getRemoteUser()); etc. } public Object get(Object key) {return CGIvariables.get(key);} } l Note that in this example, the Adapter class (CGIAdapter) itself constructs the Adaptee class (CGIVariables) Design Patterns In Java The Adapter Pattern Bob Tarr 20 10
  • 11. Adapter Pattern Example 4 l Consider a utility class that has a copy() method which can make a copy of an vector excluding those objects that meet a certain criteria. To accomplish this the method assumes that all objects in the vector implement the Copyable interface providing the isCopyable() method to determine if the object should be copied or not. Copyable Interface VectorUtilities isCopyable() BankAccount Design Patterns In Java The Adapter Pattern Bob Tarr 21 Adapter Pattern Example 4 (Continued) l Here’s the Copyable interface: public interface Copyable { public boolean isCopyable(); } l And here’s the copy() method of the VectorUtilities class: public static Vector copy(Vector vin) { Vector vout = new Vector(); Enumeration e = vin.elements(); while (e.hasMoreElements()) { Copyable c = (Copyable) e.nextElement(); if (c.isCopyable()) vout.addElemet(c); } return vout; } Design Patterns In Java The Adapter Pattern Bob Tarr 22 11
  • 12. Adapter Pattern Example 4 (Continued) l But what if we have a class, say the Document class, that does not implement the Copyable interface. We want to be able perform a selective copy of a vector of Document objects, but we do not want to modify the Document class at all. Sounds like a job for (TA-DA) an adapter! l To make things simple, let’s assume that the Document class has a nice isValid() method we can invoke to determine whether or not it should be copied Design Patterns In Java The Adapter Pattern Bob Tarr 23 Adapter Pattern Example 4 (Continued) l Here’s our new class diagram: Copyable Interface VectorUtilities isCopyable() Document DocumentAdapter isValid() Design Patterns In Java The Adapter Pattern Bob Tarr 24 12
  • 13. Adapter Pattern Example 4 (Continued) l And here is our DocumentAdapter class: public class DocumentAdapter implements Copyable { private Document d; public DocumentAdapter(Document d) { document = d; } public boolean isCopyable() { return d.isValid(); } } Design Patterns In Java The Adapter Pattern Bob Tarr 25 Adapter Pattern Example 5 l Do you see any Adapter pattern here? public class ButtonDemo { public ButtonDemo() { Button button = new Button("Press me"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doOperation(); } }); } public void doOperation() { whatever } } Design Patterns In Java The Adapter Pattern Bob Tarr 26 13
  • 14. Adapter Pattern Example 5 (Continued) l Button objects expect to be able to invoke the actionPerformed() method on their associated ActionListener objects. But the ButtonDemo class does not have this method! It really wants the button to invoke its doOperation() method. The anonymous inner class we instantiated acts as an adapter object, adapting ButtonDemo to ActionListener! Design Patterns In Java The Adapter Pattern Bob Tarr 27 14