Adapter Design Pattern

Slides:



Advertisements
Similar presentations
Design Patterns Section 7.1 (JIA’s) Section (till page 259) (JIA’s) Section 7.2.2(JIA’s) Section (JIA’s)
Advertisements

PATTERNS -STRUCTURAL PATTERNS WATTANAPON G SUTTAPAK Software Engineering, School of Information Communication Technology, University of PHAYAO 1.
Design Pattern Course Builder Pattern 1 Mahdieh Monzavi AmirKabir University of Technology, Department of Computer Engineering & Information Technology.
ADAPTER PATTERN Ali Zonoozi Design patterns course Advisor: Dr. Noorhoseini Winter 2010.
Adapters Presented By Zachary Dea. Definition A pattern found in class diagrams in which you are able to reuse an ‘adaptee’ class by providing a class,
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
1 Dept. of Computer Science & Engineering, York University, Toronto CSE3311 Software Design Adapter Pattern Façade pattern.
1 Structural Patterns  How classes and objects are composed to form larger structures  Structural class patterns: use inheritance to compose interfaces.
ADAPTER PATTERN BY Sravanthi Karumanchi. Structure Pattern Structure patterns are concerned with how classes and objects are composed to form large structures.
Object Adapter Pattern Danny Leavitt. Imagine... You program for the control center of a US phone company. Your network managment software is Object Oriented.
Partitioning and Layering Fundamentals. The Basic Problem Change is a fact of life RequirementsTechnologies Bug Fixes Software Must Adapt.
Department of Computer Science, York University Object Oriented Software Construction 13/10/ :44 AM 0 CSE3311 – Software Design Adapter Pattern.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMING PRACTICES Design patterns.
Computing IV Introduction to Design Pattern Xinwen Fu.
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
Design Patterns – II Lecture IV. Singleton Pattern Intent – Ensure a class only has one instance, and provide a global point of access to it Motivation.
Chapter 8 Object Design Reuse and Patterns. Object Design Object design is the process of adding details to the requirements analysis and making implementation.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
By Shishir Kumar Contact:
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IV Structural Patterns.
Computer Science 313 – Advanced Programming Topics.
08 - StructuralCSC4071 Structural Patterns concerned with how classes and objects are composed to form larger structures –Adapter interface converter Bridge.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Design patterns.
Object Oriented Programming
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
Class & Object Adapter Patterns (with a focus on Class Adapter) Tim Gutowski CSPP 51023, Winter 2008.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMMING PRACTICES Model View.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Adapter and Façade Patterns By Wode Ni and Leonard Bacon-Shone.
Bridge Bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently. This type of design pattern.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.
CS 350 – Software Design The Adapter Pattern – Chapter 7 Gang of Four Definition: Convert the interface of a class into another interface that the client.
Structural Patterns C h a p t e r 4 – P a g e 55 StructuralPatterns Design patterns that describe how classes and objects can be combined to form larger.
Modern Programming Tools And Techniques-I
Design Patterns: MORE Examples
Design Patterns: Brief Examples
Unit II-Chapter No. : 5- design Patterns
Design Patterns C++ Java C#.
Factory Patterns 1.
By SmartBoard team Adapter pattern.
Behavioral Design Patterns
Design Patterns C++ Java C#.
Composite Design Pattern
Design Patterns with C# (and Food!)
Advanced Programming Behnam Hatami Fall 2017.
Behavioral and Structural Patterns
Interface.
Adapter Pattern 1.
Week 6 Object-Oriented Programming (2): Polymorphism
CNT 4007C Project 2 Good morning, everyone. In this class, we will have a brief look at the project 2. Project 2 is basically the same with project 1.
Advanced Programing practices
What is Adapter Category: Structural Also known as ‘Wrapper’
Interpreter Pattern.
Structural Patterns: Adapter and Bridge
Strategy Design Pattern
Introduction to Design Patterns
Advanced ProgramMING Practices
Adapter Design Pattern
DESIGN PATTERNS : Adapter Pattern
10. Façade Pattern SE2811 Software Component Design
Advanced ProgramMING Practices
Software Design Lecture : 34.
Decorator Pattern.
Adapter Pattern Jim Fawcett
Software Design Lecture : 28.
Plug-In Architecture Pattern
Adapter Pattern Jim Fawcett
CSCI 360 Final Review Dr. X.
Presentation transcript:

Adapter Design Pattern CECS 470 Fall 2017 Mimi Opkins

Adapter Pattern Adapter is a structural design pattern, which allows incompatible objects to cooperate. Adapter acts as a wrapper between two objects, It catches calls for one object and transforms them to format and interface recognizable by the second object. In other words, how we put a square peg in a round hole.

Definition & Applicability Adapters are used to enable objects with different interfaces to communicate with each other. The Adapter pattern is used to convert the programming interface of one class into that of another. We use adapters whenever we want unrelated classes to work together in a single program. Adapters come in two flavors, object adapters and class adapters.  The concept of an adapter is thus pretty simple; we write a class that has the desired interface and then make it communicate with the class that has a different interface. Adapters in Java can be implemented in two ways: by inheritance, and by object composition.

Object Adapters Object adapters use a compositional technique to adapt one interface to another.    The adapter inherits the target interface that the client expects to see, while it holds an instance of the adaptee.   When the client calls the request() method on its target object (the adapter), the request is translated into the corresponding specific request on the adaptee. Object adapters enable the client and the adaptee to be completely decoupled from each other. Only the adapter knows about both of them.

Example 1 /** * The SquarePeg class. * This is the Target class. */ public class SquarePeg { public void insert(String str) { System.out.println("SquarePeg insert(): " + str);} } * The RoundPeg class. * This is the Adaptee class. public class RoundPeg { public void insertIntoHole(String msg) { System.out.println("RoundPeg insertIntoHole(): " + msg);}

Example 1 If a client only understands the SquarePeg interface for inserting pegs using the insert() method, how can it insert round pegs, which are pegs, but that are inserted differently, using the insertIntoHole() method?

Example 2 Solution: Design a RoundToSquarePeg adapter that enables to insertIntoHole() a RoundPeg object connected to the adapter to be inserted as a SquarePeg, using insert().

Example 2 /** * The RoundToSquarePegAdapter class. * This is the Adapter class. * It adapts a RoundPeg to a SquarePeg. * Its interface is that of a SquarePeg. */ public class RoundToSquarePegAdapter extends SquarePeg { private RoundPeg roundPeg; public RoundToSquarePegAdapter(RoundPeg peg) { //the roundPeg is plugged into the adapter this.roundPeg = peg;} public void insert(String str) { //the roundPeg can now be inserted in the same manner as a squarePeg! roundPeg.insertIntoHole(str);} }

Example 3 // 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..."); // 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! RoundToSquarePegAdapter adapter = new RoundToSquarePegAdapter(roundPeg); adapter.insert("Inserting round peg...");} }

Example 3 Execution trace: SquarePeg insert(): Inserting square peg... RoundPeg insertIntoHole(): Inserting round peg...

Class Adapters Class adapters use multiple interfaces to achieve their goals.  As in the object adapter, the class adapter inherits the interface of the client's target. However, it also inherits the interface of the adaptee as well.    Since Java does not support true multiple inheritance, this means that one of the interfaces must be inherited from a Java Interface type.  Both of the target or adaptee interfaces could be Java Interfaces.   The request to the target is simply rerouted to the specific request that was inherited from the adaptee interface.

Consequences of the Adapter Pattern Class and object adapters have different trade-offs. A class adapter: adapts Adaptee to Target by committing to a concrete Adapter class; lets Adapter override some of Adaptee's behavior, since Adapter is a subclass of Adaptee; introduces only one object, and no additional indirection is needed to get to the adaptee. An object adapter lets a single Adapter work with many Adaptees - that is, the Adaptee itself and all of its subclasses (if any). The Adapter can also add functionality to all Adaptees at once. makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making Adapter refer to the subclass rather than the Adaptee itself.

Adapter Pattern – Another Example . Adapter Pattern – Another Example Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces. This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces. A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. You plugin the memory card into card reader and card reader into the laptop so that memory card can be read via laptop. We are demonstrating use of Adapter pattern via following example in which an audio player device can play mp3 files only and wants to use an advanced audio player capable of playing vlc and mp4 files.

Implementation We have a MediaPlayer interface and a concrete class AudioPlayer implementing the MediaPlayer interface. AudioPlayer can play mp3 format audio files by default. We are having another interface AdvancedMediaPlayer and concrete classes implementing the AdvancedMediaPlayer interface. These classes can play vlc and mp4 format files. We want to make AudioPlayer to play other formats as well. To attain this, we have created an adapter class MediaAdapter which implements the MediaPlayer interface and uses AdvancedMediaPlayer objects to play the required format. AudioPlayer uses the adapter class MediaAdapter passing it the desired audio type without knowing the actual class which can play the desired format. AdapterPatternDemo, our demo class will use AudioPlayer class to play various formats.

Step 1 Create interfaces for Media Player and Advanced Media Player. MediaPlayer.java public interface MediaPlayer { public void play(String audioType, String fileName); } AdvancedMediaPlayer.java public interface AdvancedMediaPlayer { public void playVlc(String fileName); public void playMp4(String fileName);

Step 2 Create concrete classes implementing the AdvancedMediaPlayer interface. VlcPlayer.java public class VlcPlayer implements AdvancedMediaPlayer{ @Override public void playVlc(String fileName) { System.out.println("Playing vlc file. Name: "+ fileName); } public void playMp4(String fileName) { //do nothing

Step 2 Mp4Player.java public class Mp4Player implements AdvancedMediaPlayer{ @Override public void playVlc(String fileName) { //do nothing } public void playMp4(String fileName) { System.out.println("Playing mp4 file. Name: "+ fileName);

Step 3 Create adapter class implementing the MediaPlayer interface. MediaAdapter.java public class MediaAdapter implements MediaPlayer { AdvancedMediaPlayer advancedMusicPlayer; public MediaAdapter(String audioType){ if(audioType.equalsIgnoreCase("vlc") ){ advancedMusicPlayer = new VlcPlayer(); } else if (audioType.equalsIgnoreCase("mp4")){ advancedMusicPlayer = new Mp4Player(); }

Step 3 @Override public void play(String audioType, String fileName) { if(audioType.equalsIgnoreCase("vlc")){ advancedMusicPlayer.playVlc(fileName); } else if(audioType.equalsIgnoreCase("mp4")){ advancedMusicPlayer.playMp4(fileName);

Step 4 Create concrete class implementing the MediaPlayer interface. AudioPlayer.java public class AudioPlayer implements MediaPlayer { MediaAdapter mediaAdapter; @Override public void play(String audioType, String fileName) { //inbuilt support to play mp3 music files if(audioType.equalsIgnoreCase("mp3")){ System.out.println("Playing mp3 file. Name: " + fileName); }

Step 4 //mediaAdapter is providing support to play other file formats else if(audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")){ mediaAdapter = new MediaAdapter(audioType); mediaAdapter.play(audioType, fileName); } else{ System.out.println("Invalid media. " + audioType + " format not supported");

Step 5 Use the AudioPlayer to play different types of audio formats. AdapterPatternDemo.java public class AdapterPatternDemo { public static void main(String[] args) { AudioPlayer audioPlayer = new AudioPlayer(); audioPlayer.play("mp3", "beyond the horizon.mp3"); audioPlayer.play("mp4", "alone.mp4"); audioPlayer.play("vlc", "far far away.vlc"); audioPlayer.play("avi", "mind me.avi"); }

Step 6 Verify the output. Playing mp3 file. Name: beyond the horizon.mp3 Playing mp4 file. Name: alone.mp4 Playing vlc file. Name: far far away.vlc Invalid media. avi format not supported

Summary When you need to use an existing class and its interface is not the one you need, use an adapter: allows collaboration between classes with incompatible interfaces. An adapter changes an interface into one a client expects. Implementing an adapter may require little work or a great deal of work depending on the size and complexity of the target interface. There are two forms of adapter patterns: object and class adapters. Class adapters require multiple inheritance.

Credits Java Design Patterns - DEPARTMENT OF COMPUTER SCIENCE AND SOFTWARE ENGINEERING CONCORDIA UNIVERSITY - Emil Vassev, Joey Paquet : 2006-2012 Tutorials Point Design Patterns – Adapter Pattern - https://www.tutorialspoint.com/design_pattern/adapter_pattern.htm