80 likes | 303 Views
Using UML, Patterns, and Java. Object-Oriented Software Engineering. Chapter 8, Design Patterns Adapter. A Pattern Taxonomy. Pattern. Creational Pattern. Behavioral Pattern. Structural Pattern. Singleton Abstract Factory Builder Factory Prototype. Composite Decorator Adapter
E N D
Using UML, Patterns, and Java Object-Oriented Software Engineering Chapter 8, Design Patterns Adapter
A Pattern Taxonomy Pattern Creational Pattern Behavioral Pattern Structural Pattern Singleton Abstract Factory Builder Factory Prototype Composite Decorator Adapter Bridge Façade Proxy Iterator Command Observer Template Strategy
Adapter Request() Adapter pattern ClientInterface Request() Client LegacyClass ExistingRequest() • 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. • Target may be realized as an interface in Java. adaptee
Adapter Pattern • “Convert the interface of a class into another interface clients expect.” • The adapter pattern lets classes work together that couldn’t otherwise because of incompatible interfaces • Used to provide a new interface to existing legacy components (Interface engineering, reengineering). • Also known as a wrapper • Two adapter patterns: • Class adapter: • Uses multiple inheritance to adapt one interface to another • Object adapter: • Uses single inheritance and delegation • Object adapters are much more frequent.
Example: A Java Interface for a Stack public interface Stack { public void push(int x); public void pop(); public int top(); boolean empty(); } This example is borrowed from lecture notes on Design Patterns by Brian Malloy at Clemson University
The Actual Java Implementation public class FixedArray { public FixedArray() { index = -1; items = new int[10]; } public void insert(int x) { items[++index] = x; } public void removeLast() { --index; } public boolean empty() { return index == -1; } public int top() { return items[index]; } private int index; private int [] items; }
The Adapter for a Java Stack public class MyStack implements Stack { public MyStack() { array = new FixedArray(); } public void push(int x) { array.insert(x); } public void pop() { array.removeLast(); } public int top() { return array.top(); } public boolean empty() { return array.empty(); } private FixedArray array; } Notice that the adapter is implemented by using DELEGATION
Using the Java Stack public class StackTest { public static void main(String [] args) { MyStack stk = new MyStack(); stk.push(99); stk.push(7); stk.push(23); while ( !stk.empty() ) { System.out.println(stk.top()); stk.pop(); } } }