The Adapter Pattern. Wrapping Objects to Unify Interfaces

Similar documents
CMSC 132: Object-Oriented Programming II. Design Patterns I. Department of Computer Science University of Maryland, College Park

Data Structures and Algorithms

Open XML Court Interface (OXCI) Architecture Proposal

Object Oriented Software Design

Getting Started with the Internet Communications Engine

History OOP languages Year Language 1967 Simula Smalltalk

Konzepte objektorientierter Programmierung

AVRO - SERIALIZATION

Advanced OOP Concepts in Java

D06 PROGRAMMING with JAVA

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

How To Use The Command Pattern In Java.Com (Programming) To Create A Program That Is Atomic And Is Not A Command Pattern (Programmer)

Design Patterns. Advanced Software Paradigms (A. Bellaachia) 1

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Class 32: The Java Collections Framework

Contents. 9-1 Copyright (c) N. Afshartous

The Interface Concept

Adapter, Bridge, and Façade

Concepts and terminology in the Simula Programming Language

Programming Languages CIS 443

Crash Course in Java

Java Interview Questions and Answers

JAVA COLLECTIONS FRAMEWORK

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

Tools for Integration Testing

WRITING DATA TO A BINARY FILE

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Structural Design Patterns Used in Data Structures Implementation

C# and Other Languages

Iterators. Provides a way to access elements of an aggregate object sequentially without exposing its underlying representation.

Data Structures in the Java API

AP Computer Science Java Subset

1. What are Data Structures? Introduction to Data Structures. 2. What will we Study? CITS2200 Data Structures and Algorithms

Computing Concepts with Java Essentials

Implementation Aspects of OO-Languages

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. AVRO Tutorial

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Java Coding Practices for Improved Application Performance

Designing and Writing a Program DESIGNING, CODING, AND DOCUMENTING. The Design-Code-Debug Cycle. Divide and Conquer! Documentation is Code

Tutorial on Writing Modular Programs in Scala

CMSC 202H. ArrayList, Multidimensional Arrays

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Cobol. By: Steven Conner. COBOL, COmmon Business Oriented Language, one of the. oldest programming languages, was designed in the last six

Unit Testing. and. JUnit

e ag u g an L g ter lvin v E ram Neal G g ro va P Ja

Enumerated Types in Java

Practical Session 4 Java Collections

Description: Maintenance review of the JDBC RowSets 1.0 Specification. Feedback: Comments should be sent to

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

Word Count Code using MR2 Classes and API

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Collections and iterators

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

- ' +. /0 ( 1 +. ' &+. /"0 &1,

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

Object Oriented Design

Introduction: Abstract Data Types and Java Review

Tracking Load-time Configuration Options


Concrete uses of XML in software development and data analysis.

Patterns in. Lecture 2 GoF Design Patterns Creational. Sharif University of Technology. Department of Computer Engineering

An Introduction To UML Class Diagrams Classes

Introducing Variance into the Java Programming Language DRAFT

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Test-Driven Development

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

14/05/2013 Ed Merks EDL V1.0 1

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

CPLEX Tutorial Handout

Software Engineering Techniques

16.1 DataFlavor DataFlavor Methods. Variables

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Tutorial: Getting Started

Step 4: Configure a new Hadoop server This perspective will add a new snap-in to your bottom pane (along with Problems and Tasks), like so:

Creating.NET-based Mappers and Reducers for Hadoop with JNBridgePro

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Datastrukturer och standardalgoritmer i Java

Software Engineering. Top-Down Design. Bottom-Up Design. Software Process. Top-Down vs. Bottom-Up 13/02/2012

Dealing with Roles. Martin Fowler.

Compile-time type versus run-time type. Consider the parameter to this function:

Using Files as Input/Output in Java 5.0 Applications

CSE 331 Software Design & Implementation

Link-Time Static Analysis for Efficient Separate Compilation of Object-Oriented Languages

Aurora Performance Monitoring Tool Programmer s Guide by Josh Kern

How To Write A Map In Java (Java) On A Microsoft Powerbook 2.5 (Ahem) On An Ipa (Aeso) Or Ipa 2.4 (Aseo) On Your Computer Or Your Computer

Java: overview by example

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Decorator Pattern [GoF]

Exception Handling In Web Development DevelopIntelligence LLC

Transcription:

The Adapter Pattern The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn t otherwise because of incompatible interfaces. Toni Sellarès Universitat de Girona Wrapping Objects to Unify Interfaces Sometimes, an existing class may provide the functionality required by a client, but its interface may not be what the client expects. In such cases, the existing interface needs to be converted into another interface, which the client expects, preserving the reusability of the existing class. The Adapter pattern suggests defining a wrapper class around the object with the incompatible interface. This wrapper object is referred as an adapter and the object it wraps is referred to as an adaptee.

Adapter Example You have an existing software system that you need to work a new vendor library into, but the new vendor designed their interfaces differently than the last vendor. What to do? Write a class that adapts the new vendor interface into the one you re expecting. Your Existing System Vendor Class Their interface doesn t match the one you ve written your code against. Not going to work! The adapter implements the interface your classes expect Your Existing System Adapter Vendor Class And talks to the vendor interface to service your requests == Your Existing System Adapter Vendor Class No code changes New code No code changes The Adapter Pattern Defined The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn t otherwise because of incompatible interfaces. Client The client sees only the Target interface. <<Interface>> Target request ( ) The Adapter implements the target interface Full of good OO design principles: - Use of object composition - Pattern binds the client to an interface and not an implementation Adapter request ( ) Adaptee specificrequest () Adapter is composed with the Adaptee All requests get delegated to the Adaptee

Adapter Pattern Delegation is used to bind an Adapter and an Adaptee. Interface inheritance is use to specify the interface of the Adapter class. Target and Adaptee (usually called legacy system) pre-exist the Adapter. Object and Class Adapters There are two types of Adapters Object Adapter: what we have seen so far. Class Adapter: not as common as it uses multiple inheritance, which isn t possible in Java. Client <<Interface>> Target request ( ) Adaptee specificrequest () Difference: The only difference is that with class adapter we subclass the Target and the Adaptee, while the object adapter uses composition to pass requests to an adaptee. Adapter request ( ) Object Adapters and Class Adapters use two different means of adapting the adaptee: composition versus inheritance.

Adapter: Structural Example /** * This is the interface the client expects. */ public interface Target { public abstract void request(); /** * This adapts the Adaptee so the client * may use it. */ public class Adapter implements Target { private Adaptee delegate; public Adapter() { delegate = new Adaptee(); public void request() { delegate.delegatedrequest(); public class Adaptee { public void delegatedrequest() { System.out.println("This is the delegated method."); public class TestAdapter { public static void main(string[] args) { Target client = new Adapter(); client.request();

Adapter: Example 1 Old world Enumerators New world Iterators Enumeration hasmoreelements ( ) nextelement ( ) Iterator hasnext ( ) next ( ) remove ( ) Enumeration has a simple interface. Tells whether there are any more elements in the collection. Returns the next element Tells you if you have looked at all the elements And today legacy code that exposes the Enumerator interface. Yet we want new code to use Iterators. Need an adapter. Gets the next one Removes an item from the collection Adapting an Enumeration to an Iterator First step: examine the two interfaces Target interface Iterator hasnext ( ) next ( ) remove ( ) These two methods look easy, they map straight to hasnext ( ) and next ( ) in Iterator Enumeration hasmoreelements ( ) nextelement ( ) But what about this method remove ( ) in Iterator? There s nothing like that in Enumeration. Adaptee interface

Designing the Adapter Your new code gets to use Iterators, even if there s really an Enumeration underneath. Iterator hasnext ( ) next ( ) remove ( ) We are making the Enumerations in your old code look like Iterators for your new code. A class implementing the Enumeration interface is the adaptee. EnumerationIterator is the Adapter EnumerationIterator hasnext ( ) next ( ) remove ( ) Enumeration hasmoreelements () nextelement () Dealing with the remove ( ) method Enumeration is a read only interface - it does not support the remove ( ) method. Implies there is no real way to implement a fully functioning remove () method. The best that can be done is to throw a runtime exception. Iterator designers foresaw the need and have implemented an UnsupportedOperationException. Here the adapter is not perfect but is a reasonable solution as long as the client is careful and the adapter is well-documented.

EnumerationIterator - The Code public class EnumerationIterator implements Iterator { Enumeration enum; public EnumerationIterator (Enumeration enum) { this.enum = enum; public boolean hasnext () { return enum.hasmoreelements ( ); public Object next ( ) { return enum.nextelement ( ); public void remove ( ) { Since we are adapting Enumeration to Iterator, the EnumerationIterator must implement the Iterator interface -- it has to look like the Iterator. The Enumeration we are adapting. We re using composition so we stash it in an instance variable. hasnext ( ) and next () are implemented by delegating to the appropriate methods in the Enumeration. throw new UnsupportedOperationException ( For ); the remove ( ) we simply throw an exception. Adapter: Example 2 Adapt from integer Set to integer Priority Queue Original Integer set does not support Priority Queue. Using Adapter pattern Adapter provides interface for using Set as Priority Queue. Add needed functionality in Adapter methods.

public interface PriorityQueue { void add(object o); int size(); Object removesmallest(); // Priority Queue public class PriorityQueueAdapter implements PriorityQueue { Set s; PriorityQueueAdapter(Set s){ this.s = s; public void add(object o){ s.add(o); int size(){ return s.size(); public Integer removesmallest() { Integer smallest = Integer.MAX_VALUE; Iterator it = s.iterator(); while ( it.hasnext() ) { Integer i = it.next(); if (i.compareto(smallest) < 0) smallest = i; s.remove(smallest); return smallest; 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.