SlideShare a Scribd company logo
1 of 28
Structural Patterns
               The Adapter Pattern

                   Design Patterns
                     Chapter 8A




Dec 21, 2012     Design Patterns Chapter 8A1
Objectives

 In this lecture, we will
 • Review structural design patterns
 • Discuss why such patterns are useful
 • Introduce the Adapter pattern
 • Discuss examples that take advantage of the adapter
    pattern




Dec 21, 2012       Design Patterns Chapter 8A2
Structural Patterns

 • Structural Patterns are used when it is necessary to build
   larger structures that are composed of other existing
   classes and objects
     – Re-use of existing implementations
 • Structural class patterns use inheritance
 • Structural object patterns use aggregation


 • This lecture introduces the adapter pattern




Dec 21, 2012         Design Patterns Chapter 8A3
What is an Adapter?

 • A simple example of an adapter is an electric razor
   adapter
 • Most British domestic sockets are standard three pin
   sockets
     – live, neutral and earth
 • Most electric razors come with a two pin plug
     – That will not push into a three pin socket
 • An electric razor adapter provides the link between the
   two
     – Modifies the interface of the razor to make it compatible with
       the three pin socket
 • What about British and Continental sockets?

Dec 21, 2012           Design Patterns Chapter 8A4
Software Adapters

 • In object oriented programming the same type of problem
   often arises
 • A class, XClass, has been built and works well
 • A system has been built that works with objects that
   satisfy a certain interface
 • The methods of the XClass provide all the functionality
   required of the objects that work with the system
 • BUT the interface of the XClass is not the interface
   required by the system
 • What is the easiest solution that re-uses the XClass?
     – Write an adapter!



Dec 21, 2012         Design Patterns Chapter 8A5
Dialog Boxes

 • How is a dialog box displayed in Java?
   JOptionPane.showMessageDialog ( null, “This is a TEST” );
 • What is displayed?




  • Where does the image come from?
  • Can the image be changed?


Dec 21, 2012         Design Patterns Chapter 8A6
The showMessageDialog method

 • The declaration of this method is:
   public static void showMessageDialog
   {
        Component parent,
        Object       message,
        String       title,
        int          messageType,
        Icon        anIcon
   }
 • The last parameter is of type Icon; an interface
     – Any object that implements the Icon interface can be used


Dec 21, 2012          Design Patterns Chapter 8A7
Using an ImageIcon

 • The ImageIcon class implements the Icon interface and can
   build an icon from a GIF file
 • For example:
    JOptionPane.showMessageDialog (
        null,                            // parent
        "Hello",                                   // message
        "Testing GIF",                             // title
        JOptionPane.INFORMATION_MESSAGE,                     // messageType
        new ImageIcon("c:tempduke.gif")        // anIcon
     );




Dec 21, 2012              Design Patterns Chapter 8A8
What is the Icon interface?

 • The definition of an Icon interface is:
     public interface Icon
     {
         int getIconWidth () ;
         int getIconHeight ();
         void paintIcon ( Component c, Graphics g, int x, int y);
     }




Dec 21, 2012           Design Patterns Chapter 8A9
A Simple Icon Class
 public class PeteIcon implements Icon {
   private int size;
   public PeteIcon(int aSize) { size = aSize; }
   public int getIconWidth() { return size; }
   public int getIconHeight() { return size; }
   public void paintIcon (Component c, Graphics g, int x, int y)
   {
      Graphics2D g2 = (Graphics2D) g;
      Ellipse2D.Double e = new Ellipse2D.Double (x,y,size,size);
      g2.setColor (Color.RED);
      g2.fill(e);
      g2.setColor(Color.BLACK);
      g2.drawString("Pete",size/3,size/2);
   }
 }

Dec 21, 2012          Design Patterns Chapter 8A10
Using the Icon Class

 • An instance of PeteIcon can be used anywhere an Icon is
   expected:
  JOptionPane.showMessageDialog (
    null, "Hello", "Testing PeteIcon",
    JOptionPane.INFORMATION_MESSAGE, new PeteIcon(100)
 );




Dec 21, 2012         Design Patterns Chapter 8A11
Building a User Interface

 • In building a user interface frames are often used to
   contain a set of user interface components
     JFrame frame = new JFrame();
     Container contentPane = frame.getContentPane();
     JButton b1 = new JButton("Push");
     contentPane.add(b1,BorderLayout.NORTH);
     JButton b2 = new JButton("STOP");
     contentPane.add(b2,BorderLayout.SOUTH);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.pack();
     frame.show();
 • The frame has a container that manages a collection of
   components; a button is an example of a JComponent

Dec 21, 2012        Design Patterns Chapter 8A12
What is a JComponent

 • JComponent is a superclass used in developing user
   interface components
     – JButton extends JComponent
 • JComponent provides implementations for the methods
   that are used by a container
 • Two key methods are:
     – paintComponent that draws the component
     – getPrefferedSize that returns the preferred dimension of a
       component
 • A PeteIcon knows how to draw itself and can return both a
   width and a height
     – But it cannot be used in place of a JComponent
     – The interface does not match


Dec 21, 2012          Design Patterns Chapter 8A13
Using an Adapter

 • An adapter is needed to use an instance of an Icon to fulfil
   the role of a JComponent
     – An Icon has the appropriate functionality but an
       inappropriate interface
 • The adapter must extend the JComponent class and
   contain an instance of an icon to do the work
     – Calling a method of the adapter may result in a call to a
       method of the contained icon




Dec 21, 2012          Design Patterns Chapter 8A14
An Icon Adapter Class
 public class IconAdapter extends JComponent
 {
    private Icon icon;
    public IconAdapter (Icon aIcon)
   { this.icon = aIcon; }
    public void paintComponent(Graphics g)
   { icon.paintIcon(this,g,0,0); }
    public Dimension getPreferredSize()
    {
       return new Dimension(       icon.getIconWidth(),
                                   icon.getIconHeight());
    }

 }


Dec 21, 2012           Design Patterns Chapter 8A15
Using the Adapter

 • An instance of an IconAdapter can be used as a component
     – Built from an instance of any Icon
 • For example:
     JComponent c = new IconAdapter ( new PeteIcon(100)) ;
     contentPane.add(c,BorderLayout.CENTER);


 • Although a PeteIcon is used here any                      Icon
   could be used
     – The IconAdapter adapts an Icon




Dec 21, 2012            Design Patterns Chapter 8A16
Using the Adapter Class


    JFrame       JComponent
                                             «interface»
               +paintComponent()                Icon
               +getPreferredSize()



                  IconAdapter                PeteIcon


               +paintComponent()
                                     1   1
               +getPreferredSize()




Dec 21, 2012    Design Patterns Chapter 8A17
The Adapter Pattern

 • This is an example of the adapter pattern
     – Used as a structural object pattern


 • The situation in which the pattern is useful can be
   summed up as:
     – You want to use an existing class, called the adaptee,
       without modifying it
     – The system in which the class is to be used requires
       conformance to a target interface that is different to the
       interface of the adaptee
     – The adaptee has the functionality required by the target
       interface


Dec 21, 2012           Design Patterns Chapter 8A18
The Adapter Pattern

 • Intent
     – Convert the interface of a class into another interface; the
       interface expected by a client
     – The adapter lets classes work together that could not do so
       otherwise because of incompatible interfaces
 • Also known as Wrapper
 • Applicability
   Use the adapter pattern when:
     – You want to use an existing class, and its interface does not
       match the one that you need
     – You want to create a re-useable class that co-operates with
       unrelated or unforeseen classes


Dec 21, 2012          Design Patterns Chapter 8A19
The Adapter Pattern

 Participants
 • Target
     – Defines the domain-specific interface that the Client uses
 • Client
     – Collaborates with objects that conform to the Target
       interface
 • Adaptee
     – Defines an existing interface that needs to be adapted
 • Adapter
     – Adapts the interface of the Adaptee to the Target interface




Dec 21, 2012          Design Patterns Chapter 8A20
The Adapter Pattern

 • Structure
     – An object adapter relies on object composition:




Dec 21, 2012            Design Patterns Chapter 8A21
The Adapter Pattern

 • Structure
     – A class adapter uses multiple inheritance




Dec 21, 2012            Design Patterns Chapter 8A22
Consequences – The Class Adapter

 • A class Adapter adapts an Adaptee to a Target by
   commiting to a concrete Adaptee class
     – As a consequence it is not possible to adapt a class and all
       of its subclasses
 • A class Adapter allows the Adapter to override some of
   the Adaptee’s behaviour
     – because the Adapter is a subclass of the Adaptee
 • A class Adapter introduces only one object and therefore
   no additional runtime overhead for method invocation


 • Now compare these trade offs with an object adapter


Dec 21, 2012          Design Patterns Chapter 8A23
Consequences – The Object Adapter

 • An Object Adapter allows a single adapter to work with
   many Adpatees
     – The Adaptee itself and any subclasses of the Adaptee
     – The Adapter can add functionality to all Adaptees at once
 • An Object Adapter makes it harder to override Adaptee
   behaviour
     – It is necessary to subclass the Adpatee and ensure that the
       Adapter refers to the subclass rather than to the original
       Adaptee




Dec 21, 2012          Design Patterns Chapter 8A24
How much adapting does an Adapter
 do?
 • In the example seen earlier in this lecture the adapter did
   little more than interface conversion
     – It changed the name of one method
     – It implemented another method of the target interface by
       calling two methods of the adaptee interface
 • In other examples an adapter may do much more
     – It may use several methods of an adaptee plus some
       additional code to implement a method of the target interface
     – It may add additional behaviour, not provided in the adaptee,
       in order to fulfil the interface requirements of the target




Dec 21, 2012          Design Patterns Chapter 8A25
Java and Design Patterns

 • The Java language contains many examples of the use of
   design patterns
 • For example consider the case where you have an input
   stream and you need a reader
     – An input stream reads bytes
     – A reader reads characters
     – The difference between the two is significant in many
       languages
 • In Java an InputStreamReader adapter is used
     – Reader myReader = new InputStreamReader (System.in);




Dec 21, 2012          Design Patterns Chapter 8A26
Java InputStreamReader Adapter

 • In this case:


    Adaptee           InputStream
    Target            Reader
    Adapter           InputStreamReader
    Client            the class that wants to read text from
                      an input stream


 • As an exercise search for as many examples of the use of
   the adapter pattern as you can find in Java



Dec 21, 2012       Design Patterns Chapter 8A27
Summary

 In this lecture we have:
 • Reviewed structural design patterns
 • Discussed why such patterns are useful
 • Introduced the Adapter pattern
 • Discussed examples that take advantage of the adapter
    pattern




Dec 21, 2012       Design Patterns Chapter 8A28

More Related Content

What's hot

What's hot (8)

Ch02lect1 ud
Ch02lect1 udCh02lect1 ud
Ch02lect1 ud
 
Ch04lect1 ud
Ch04lect1 udCh04lect1 ud
Ch04lect1 ud
 
Ch03lect2 ud
Ch03lect2 udCh03lect2 ud
Ch03lect2 ud
 
Ch05lect2 ud
Ch05lect2 udCh05lect2 ud
Ch05lect2 ud
 
Ch01lect1 ud
Ch01lect1 udCh01lect1 ud
Ch01lect1 ud
 
Executable UML and SysML Workshop
Executable UML and SysML WorkshopExecutable UML and SysML Workshop
Executable UML and SysML Workshop
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
UML as a Programming Language
UML as a Programming LanguageUML as a Programming Language
UML as a Programming Language
 

Viewers also liked

Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Patternguy_davis
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design PatternAdeel Riaz
 
Proxy & adapter pattern
Proxy & adapter patternProxy & adapter pattern
Proxy & adapter patternbabak danyal
 
Design Patterns Part1
Design Patterns  Part1Design Patterns  Part1
Design Patterns Part1Tom Chen
 
Adapter design-pattern2015
Adapter design-pattern2015Adapter design-pattern2015
Adapter design-pattern2015Vic Tarchenko
 
The 23 gof design patterns in java ,the summary
The 23 gof design patterns in java ,the summaryThe 23 gof design patterns in java ,the summary
The 23 gof design patterns in java ,the summaryachraf_ing
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - AdapterManoj Kumar
 
Bridge pattern for Dummies
Bridge pattern for DummiesBridge pattern for Dummies
Bridge pattern for DummiesTaekSoon Jang
 
Design Patterns - 04 Adapter and Facade Pattern
Design Patterns - 04 Adapter and Facade PatternDesign Patterns - 04 Adapter and Facade Pattern
Design Patterns - 04 Adapter and Facade Patterneprafulla
 
Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patternsLilia Sfaxi
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
Design pattern tutorial
Design pattern tutorialDesign pattern tutorial
Design pattern tutorialPiyush Mittal
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design patternMindfire Solutions
 
Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns pptAman Jain
 
Implementing the Adapter Design Pattern
Implementing the Adapter Design PatternImplementing the Adapter Design Pattern
Implementing the Adapter Design PatternProdigyView
 
Design Patterns & JDK Examples
Design Patterns & JDK ExamplesDesign Patterns & JDK Examples
Design Patterns & JDK ExamplesEnder Aydin Orak
 

Viewers also liked (20)

Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Proxy & adapter pattern
Proxy & adapter patternProxy & adapter pattern
Proxy & adapter pattern
 
Design Patterns Part1
Design Patterns  Part1Design Patterns  Part1
Design Patterns Part1
 
Adapter design-pattern2015
Adapter design-pattern2015Adapter design-pattern2015
Adapter design-pattern2015
 
The 23 gof design patterns in java ,the summary
The 23 gof design patterns in java ,the summaryThe 23 gof design patterns in java ,the summary
The 23 gof design patterns in java ,the summary
 
Structural Design pattern - Adapter
Structural Design pattern - AdapterStructural Design pattern - Adapter
Structural Design pattern - Adapter
 
Design patterns - Adapter Pattern
Design patterns - Adapter PatternDesign patterns - Adapter Pattern
Design patterns - Adapter Pattern
 
Bridge pattern for Dummies
Bridge pattern for DummiesBridge pattern for Dummies
Bridge pattern for Dummies
 
Design Patterns - 04 Adapter and Facade Pattern
Design Patterns - 04 Adapter and Facade PatternDesign Patterns - 04 Adapter and Facade Pattern
Design Patterns - 04 Adapter and Facade Pattern
 
Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patterns
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Design pattern tutorial
Design pattern tutorialDesign pattern tutorial
Design pattern tutorial
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Implementing the Adapter Design Pattern
Implementing the Adapter Design PatternImplementing the Adapter Design Pattern
Implementing the Adapter Design Pattern
 
Design Patterns & JDK Examples
Design Patterns & JDK ExamplesDesign Patterns & JDK Examples
Design Patterns & JDK Examples
 

Similar to Design patterns structuralpatterns(theadapterpattern)

Design Patterns By Sisimon Soman
Design Patterns By Sisimon SomanDesign Patterns By Sisimon Soman
Design Patterns By Sisimon SomanSisimon Soman
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSoftware Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSergey Aganezov
 
Angularjs2 presentation
Angularjs2 presentationAngularjs2 presentation
Angularjs2 presentationdharisk
 
Design patterns 1july
Design patterns 1julyDesign patterns 1july
Design patterns 1julyEdureka!
 
Ad103 - Have it Your Way: Extending IBM Lotus Domino Designer
Ad103 - Have it Your Way: Extending IBM Lotus Domino DesignerAd103 - Have it Your Way: Extending IBM Lotus Domino Designer
Ad103 - Have it Your Way: Extending IBM Lotus Domino Designerddrschiw
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
Webinar on Design Patterns titled 'Dive into Design Patterns'
Webinar on Design Patterns titled 'Dive into Design Patterns'Webinar on Design Patterns titled 'Dive into Design Patterns'
Webinar on Design Patterns titled 'Dive into Design Patterns'Edureka!
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxdanhaley45372
 
SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"Inhacking
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Design Patterns : The Ultimate Blueprint for Software
Design Patterns : The Ultimate Blueprint for SoftwareDesign Patterns : The Ultimate Blueprint for Software
Design Patterns : The Ultimate Blueprint for SoftwareEdureka!
 
Schematics designer tutorial_i
Schematics designer tutorial_iSchematics designer tutorial_i
Schematics designer tutorial_iguestc78605
 
Building modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf FildebrandtBuilding modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf Fildebrandtmfrancis
 

Similar to Design patterns structuralpatterns(theadapterpattern) (20)

Design Patterns By Sisimon Soman
Design Patterns By Sisimon SomanDesign Patterns By Sisimon Soman
Design Patterns By Sisimon Soman
 
Software Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural PatternsSoftware Design Patterns. Part I :: Structural Patterns
Software Design Patterns. Part I :: Structural Patterns
 
Angularjs2 presentation
Angularjs2 presentationAngularjs2 presentation
Angularjs2 presentation
 
Lecture11
Lecture11Lecture11
Lecture11
 
Design patterns 1july
Design patterns 1julyDesign patterns 1july
Design patterns 1july
 
Ad103 - Have it Your Way: Extending IBM Lotus Domino Designer
Ad103 - Have it Your Way: Extending IBM Lotus Domino DesignerAd103 - Have it Your Way: Extending IBM Lotus Domino Designer
Ad103 - Have it Your Way: Extending IBM Lotus Domino Designer
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Webinar on Design Patterns titled 'Dive into Design Patterns'
Webinar on Design Patterns titled 'Dive into Design Patterns'Webinar on Design Patterns titled 'Dive into Design Patterns'
Webinar on Design Patterns titled 'Dive into Design Patterns'
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"
 
Alex Theedom Java ee revisits design patterns
Alex Theedom	Java ee revisits design patternsAlex Theedom	Java ee revisits design patterns
Alex Theedom Java ee revisits design patterns
 
Introduction to Objective - C
Introduction to Objective - CIntroduction to Objective - C
Introduction to Objective - C
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Angularj2.0
Angularj2.0Angularj2.0
Angularj2.0
 
Decorator Pattern
Decorator PatternDecorator Pattern
Decorator Pattern
 
Design Patterns : The Ultimate Blueprint for Software
Design Patterns : The Ultimate Blueprint for SoftwareDesign Patterns : The Ultimate Blueprint for Software
Design Patterns : The Ultimate Blueprint for Software
 
Design patterns tutorials
Design patterns tutorialsDesign patterns tutorials
Design patterns tutorials
 
Schematics designer tutorial_i
Schematics designer tutorial_iSchematics designer tutorial_i
Schematics designer tutorial_i
 
Building modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf FildebrandtBuilding modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf Fildebrandt
 

More from APU

01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_moduleAPU
 
. 1. introduction to object orientation
. 1. introduction to object orientation. 1. introduction to object orientation
. 1. introduction to object orientationAPU
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_moduleAPU
 
9. oo languages
9. oo languages9. oo languages
9. oo languagesAPU
 
8. design patterns
8. design patterns8. design patterns
8. design patternsAPU
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams7. sequence and collaboration diagrams
7. sequence and collaboration diagramsAPU
 
6. activity diagrams
6. activity diagrams6. activity diagrams
6. activity diagramsAPU
 
5. state diagrams
5. state diagrams5. state diagrams
5. state diagramsAPU
 
4. class diagrams using uml
4. class diagrams using uml4. class diagrams using uml
4. class diagrams using umlAPU
 
3. use cases
3. use cases3. use cases
3. use casesAPU
 
01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_moduleAPU
 
. 9. oo languages
. 9. oo languages. 9. oo languages
. 9. oo languagesAPU
 
08 aggregation and collection classes
08  aggregation and collection classes08  aggregation and collection classes
08 aggregation and collection classesAPU
 
. 8. design patterns
. 8. design patterns. 8. design patterns
. 8. design patternsAPU
 
. 5. state diagrams
. 5. state diagrams. 5. state diagrams
. 5. state diagramsAPU
 
. 4. class diagrams using uml
. 4. class diagrams using uml. 4. class diagrams using uml
. 4. class diagrams using umlAPU
 
. 2. introduction to uml
. 2. introduction to uml. 2. introduction to uml
. 2. introduction to umlAPU
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_moduleAPU
 
14 file handling
14 file handling14 file handling
14 file handlingAPU
 
13 gui development
13 gui development13 gui development
13 gui developmentAPU
 

More from APU (20)

01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
 
. 1. introduction to object orientation
. 1. introduction to object orientation. 1. introduction to object orientation
. 1. introduction to object orientation
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_module
 
9. oo languages
9. oo languages9. oo languages
9. oo languages
 
8. design patterns
8. design patterns8. design patterns
8. design patterns
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams7. sequence and collaboration diagrams
7. sequence and collaboration diagrams
 
6. activity diagrams
6. activity diagrams6. activity diagrams
6. activity diagrams
 
5. state diagrams
5. state diagrams5. state diagrams
5. state diagrams
 
4. class diagrams using uml
4. class diagrams using uml4. class diagrams using uml
4. class diagrams using uml
 
3. use cases
3. use cases3. use cases
3. use cases
 
01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
 
. 9. oo languages
. 9. oo languages. 9. oo languages
. 9. oo languages
 
08 aggregation and collection classes
08  aggregation and collection classes08  aggregation and collection classes
08 aggregation and collection classes
 
. 8. design patterns
. 8. design patterns. 8. design patterns
. 8. design patterns
 
. 5. state diagrams
. 5. state diagrams. 5. state diagrams
. 5. state diagrams
 
. 4. class diagrams using uml
. 4. class diagrams using uml. 4. class diagrams using uml
. 4. class diagrams using uml
 
. 2. introduction to uml
. 2. introduction to uml. 2. introduction to uml
. 2. introduction to uml
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_module
 
14 file handling
14 file handling14 file handling
14 file handling
 
13 gui development
13 gui development13 gui development
13 gui development
 

Design patterns structuralpatterns(theadapterpattern)

  • 1. Structural Patterns The Adapter Pattern Design Patterns Chapter 8A Dec 21, 2012 Design Patterns Chapter 8A1
  • 2. Objectives In this lecture, we will • Review structural design patterns • Discuss why such patterns are useful • Introduce the Adapter pattern • Discuss examples that take advantage of the adapter pattern Dec 21, 2012 Design Patterns Chapter 8A2
  • 3. Structural Patterns • Structural Patterns are used when it is necessary to build larger structures that are composed of other existing classes and objects – Re-use of existing implementations • Structural class patterns use inheritance • Structural object patterns use aggregation • This lecture introduces the adapter pattern Dec 21, 2012 Design Patterns Chapter 8A3
  • 4. What is an Adapter? • A simple example of an adapter is an electric razor adapter • Most British domestic sockets are standard three pin sockets – live, neutral and earth • Most electric razors come with a two pin plug – That will not push into a three pin socket • An electric razor adapter provides the link between the two – Modifies the interface of the razor to make it compatible with the three pin socket • What about British and Continental sockets? Dec 21, 2012 Design Patterns Chapter 8A4
  • 5. Software Adapters • In object oriented programming the same type of problem often arises • A class, XClass, has been built and works well • A system has been built that works with objects that satisfy a certain interface • The methods of the XClass provide all the functionality required of the objects that work with the system • BUT the interface of the XClass is not the interface required by the system • What is the easiest solution that re-uses the XClass? – Write an adapter! Dec 21, 2012 Design Patterns Chapter 8A5
  • 6. Dialog Boxes • How is a dialog box displayed in Java? JOptionPane.showMessageDialog ( null, “This is a TEST” ); • What is displayed? • Where does the image come from? • Can the image be changed? Dec 21, 2012 Design Patterns Chapter 8A6
  • 7. The showMessageDialog method • The declaration of this method is: public static void showMessageDialog { Component parent, Object message, String title, int messageType, Icon anIcon } • The last parameter is of type Icon; an interface – Any object that implements the Icon interface can be used Dec 21, 2012 Design Patterns Chapter 8A7
  • 8. Using an ImageIcon • The ImageIcon class implements the Icon interface and can build an icon from a GIF file • For example: JOptionPane.showMessageDialog ( null, // parent "Hello", // message "Testing GIF", // title JOptionPane.INFORMATION_MESSAGE, // messageType new ImageIcon("c:tempduke.gif") // anIcon ); Dec 21, 2012 Design Patterns Chapter 8A8
  • 9. What is the Icon interface? • The definition of an Icon interface is: public interface Icon { int getIconWidth () ; int getIconHeight (); void paintIcon ( Component c, Graphics g, int x, int y); } Dec 21, 2012 Design Patterns Chapter 8A9
  • 10. A Simple Icon Class public class PeteIcon implements Icon { private int size; public PeteIcon(int aSize) { size = aSize; } public int getIconWidth() { return size; } public int getIconHeight() { return size; } public void paintIcon (Component c, Graphics g, int x, int y) { Graphics2D g2 = (Graphics2D) g; Ellipse2D.Double e = new Ellipse2D.Double (x,y,size,size); g2.setColor (Color.RED); g2.fill(e); g2.setColor(Color.BLACK); g2.drawString("Pete",size/3,size/2); } } Dec 21, 2012 Design Patterns Chapter 8A10
  • 11. Using the Icon Class • An instance of PeteIcon can be used anywhere an Icon is expected: JOptionPane.showMessageDialog ( null, "Hello", "Testing PeteIcon", JOptionPane.INFORMATION_MESSAGE, new PeteIcon(100) ); Dec 21, 2012 Design Patterns Chapter 8A11
  • 12. Building a User Interface • In building a user interface frames are often used to contain a set of user interface components JFrame frame = new JFrame(); Container contentPane = frame.getContentPane(); JButton b1 = new JButton("Push"); contentPane.add(b1,BorderLayout.NORTH); JButton b2 = new JButton("STOP"); contentPane.add(b2,BorderLayout.SOUTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.show(); • The frame has a container that manages a collection of components; a button is an example of a JComponent Dec 21, 2012 Design Patterns Chapter 8A12
  • 13. What is a JComponent • JComponent is a superclass used in developing user interface components – JButton extends JComponent • JComponent provides implementations for the methods that are used by a container • Two key methods are: – paintComponent that draws the component – getPrefferedSize that returns the preferred dimension of a component • A PeteIcon knows how to draw itself and can return both a width and a height – But it cannot be used in place of a JComponent – The interface does not match Dec 21, 2012 Design Patterns Chapter 8A13
  • 14. Using an Adapter • An adapter is needed to use an instance of an Icon to fulfil the role of a JComponent – An Icon has the appropriate functionality but an inappropriate interface • The adapter must extend the JComponent class and contain an instance of an icon to do the work – Calling a method of the adapter may result in a call to a method of the contained icon Dec 21, 2012 Design Patterns Chapter 8A14
  • 15. An Icon Adapter Class public class IconAdapter extends JComponent { private Icon icon; public IconAdapter (Icon aIcon) { this.icon = aIcon; } public void paintComponent(Graphics g) { icon.paintIcon(this,g,0,0); } public Dimension getPreferredSize() { return new Dimension( icon.getIconWidth(), icon.getIconHeight()); } } Dec 21, 2012 Design Patterns Chapter 8A15
  • 16. Using the Adapter • An instance of an IconAdapter can be used as a component – Built from an instance of any Icon • For example: JComponent c = new IconAdapter ( new PeteIcon(100)) ; contentPane.add(c,BorderLayout.CENTER); • Although a PeteIcon is used here any Icon could be used – The IconAdapter adapts an Icon Dec 21, 2012 Design Patterns Chapter 8A16
  • 17. Using the Adapter Class JFrame JComponent «interface» +paintComponent() Icon +getPreferredSize() IconAdapter PeteIcon +paintComponent() 1 1 +getPreferredSize() Dec 21, 2012 Design Patterns Chapter 8A17
  • 18. The Adapter Pattern • This is an example of the adapter pattern – Used as a structural object pattern • The situation in which the pattern is useful can be summed up as: – You want to use an existing class, called the adaptee, without modifying it – The system in which the class is to be used requires conformance to a target interface that is different to the interface of the adaptee – The adaptee has the functionality required by the target interface Dec 21, 2012 Design Patterns Chapter 8A18
  • 19. The Adapter Pattern • Intent – Convert the interface of a class into another interface; the interface expected by a client – The adapter lets classes work together that could not do so otherwise because of incompatible interfaces • Also known as Wrapper • Applicability Use the adapter pattern when: – You want to use an existing class, and its interface does not match the one that you need – You want to create a re-useable class that co-operates with unrelated or unforeseen classes Dec 21, 2012 Design Patterns Chapter 8A19
  • 20. The Adapter Pattern Participants • Target – Defines the domain-specific interface that the Client uses • Client – Collaborates with objects that conform to the Target interface • Adaptee – Defines an existing interface that needs to be adapted • Adapter – Adapts the interface of the Adaptee to the Target interface Dec 21, 2012 Design Patterns Chapter 8A20
  • 21. The Adapter Pattern • Structure – An object adapter relies on object composition: Dec 21, 2012 Design Patterns Chapter 8A21
  • 22. The Adapter Pattern • Structure – A class adapter uses multiple inheritance Dec 21, 2012 Design Patterns Chapter 8A22
  • 23. Consequences – The Class Adapter • A class Adapter adapts an Adaptee to a Target by commiting to a concrete Adaptee class – As a consequence it is not possible to adapt a class and all of its subclasses • A class Adapter allows the Adapter to override some of the Adaptee’s behaviour – because the Adapter is a subclass of the Adaptee • A class Adapter introduces only one object and therefore no additional runtime overhead for method invocation • Now compare these trade offs with an object adapter Dec 21, 2012 Design Patterns Chapter 8A23
  • 24. Consequences – The Object Adapter • An Object Adapter allows a single adapter to work with many Adpatees – The Adaptee itself and any subclasses of the Adaptee – The Adapter can add functionality to all Adaptees at once • An Object Adapter makes it harder to override Adaptee behaviour – It is necessary to subclass the Adpatee and ensure that the Adapter refers to the subclass rather than to the original Adaptee Dec 21, 2012 Design Patterns Chapter 8A24
  • 25. How much adapting does an Adapter do? • In the example seen earlier in this lecture the adapter did little more than interface conversion – It changed the name of one method – It implemented another method of the target interface by calling two methods of the adaptee interface • In other examples an adapter may do much more – It may use several methods of an adaptee plus some additional code to implement a method of the target interface – It may add additional behaviour, not provided in the adaptee, in order to fulfil the interface requirements of the target Dec 21, 2012 Design Patterns Chapter 8A25
  • 26. Java and Design Patterns • The Java language contains many examples of the use of design patterns • For example consider the case where you have an input stream and you need a reader – An input stream reads bytes – A reader reads characters – The difference between the two is significant in many languages • In Java an InputStreamReader adapter is used – Reader myReader = new InputStreamReader (System.in); Dec 21, 2012 Design Patterns Chapter 8A26
  • 27. Java InputStreamReader Adapter • In this case: Adaptee InputStream Target Reader Adapter InputStreamReader Client the class that wants to read text from an input stream • As an exercise search for as many examples of the use of the adapter pattern as you can find in Java Dec 21, 2012 Design Patterns Chapter 8A27
  • 28. Summary In this lecture we have: • Reviewed structural design patterns • Discussed why such patterns are useful • Introduced the Adapter pattern • Discussed examples that take advantage of the adapter pattern Dec 21, 2012 Design Patterns Chapter 8A28

Editor's Notes

  1. Part of this lecture will be reserved for working through solutions to selected exercises from last week. Notes relating to this do not appear in the slides.