Presentation is loading. Please wait.

Presentation is loading. Please wait.

3-1 Three Design Patterns: Adapter, Façade, Flyweight C Sc 335 Rick Mercer.

Similar presentations

Presentation on theme: "3-1 Three Design Patterns: Adapter, Façade, Flyweight C Sc 335 Rick Mercer."— Presentation transcript:

1 3-1 Three Design Patterns: Adapter, Façade, Flyweight C Sc 335 Rick Mercer

2 Adapter Design Pattern Gang of Four state the intent of Adapter is to Convert the interface of a class into another interface that the clients expect. Adapter lets classes work together that could not otherwise because of incompatible interfaces.

3 Adapter Design Pattern Problem: An "off the shelf" component offers compelling functionality that you would like to reuse, but its "view of the world" is not compatible with the philosophy and architecture of the new system Adapter is about creating an intermediary abstraction that translates, or maps, the old component to the new system Use Adapter when you need a way to create a new interface for an object that does the right stuff but has the wrong interface

4 Adapter Can be thought of as a Wrapper

5 Example Object Adapter Before Java 5.0, we often adapted an ArrayList or HashMap to have an easier to use collection Used a Containment Relationship with a collection using an ArrayList or HashMap instance variable Put the cast in the method once instead of everywhere Add Employees rather than Objects (type safe) Method names then mean more to the clients Employee getEmployeeWithID (String) good Object getEmployeeWithID (String) bad

6 Object Adapters Object Adapters rely on one object (the adapting object) containing another (the adapted object) A Stack class should have a Vector and use only Vector’s add, get, and size methods (aka Wrapper) Stack should not extend Vector: java.lang.Object java.util.AbstractCollection java.util.AbstractList java.util.Vector java.util.Stack

7 7 Class Adapters Class Adapters also come about by extending a class or implementing an interface used by the client code You may have used class adapters already Adapt a song collection so it could be stored in a ListModel object, which in turn was used by a JList to show a graphical view of the list elements JList needs the methods defined in the ListModel interface: getSize() and getElementAt(int) Adapt a model to the interface needed by JList

8 interface TableModel also adapts A JTable requires a TableModel object that represents the data (model) JTable expects your model to have getColumnCount, getRowCount, getValueAt JTable uses these methods to display view Need to adapt the model to what JTable expects Adapt the model class to the interface expected by JTable by implementing all 10 methods in the model

9 Adapt a collection into a TableModel JTable can shows a list of Employees like this

10 EmployeeList adapted to TableModel public class EmployeeList implements TableModel { private ArrayList data = new ArrayList (); public EmployeeList() { data.add(new Employee("Devon", 40, 15.75, 3, "M")); data.add(new Employee("Kim", 0, 12.50, 1, "S")); data.add(new Employee("Chris", 35, 20.50, 2, "M")); } public void add(Employee employee) { data.add(employee); } public Iterator iterator() { return data.iterator(); }

11 A TabelModel method helps adapt // Adapt tax and pay methods to getValueAt(int column) public Object getValueAt(int rowIndex, int columnIndex) { Employee currentEmployee = data.get(rowIndex); double totalTaxes = currentEmployee.incomeTax() + currentEmployee.medicareTax() + currentEmployee.socialSecurityTax(); switch (columnIndex) { case 0: return currentEmployee.getName(); case 1: return currentEmployee.grossPay(); case 2: return totalTaxes; case 3: return data.get(rowIndex).grossPay() - totalTaxes; default: return null; }

12 A View, which is the Client class EmployeeFrame extends JFrame { public static void main(String[] args) { new EmployeeFrame().setVisible(true); } private EmployeeList threeEmps; public EmployeeFrame() { threeEmps = new EmployeeList(); EmployeeList threeEmps = new EmployeeList(); setSize(300, 120); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTable view = new JTable(threeEmps); this.add(view, BorderLayout.CENTER); }

13 Adapter Example & General Form Client: EmployFrame Adapter: JTable Adaptee: EmployeeList

14 Other Adapter Classes The WindowListener interface has seven methods that you must implement If you only need to respond to one window event, you can extend WindowAdapter and override whatever methods you need to Terminator extends WindowAdapter { private class Terminator extends WindowAdapter { // This is a WindowAdapter, methods do nothing // This is a WindowAdapter, methods do nothing WindowClosing(WindowEvent e) { public void WindowClosing(WindowEvent e) { System.exit(0); System.exit(0); } // the other 6 methods are in WindowAdapter // and they are set to do nothing // the other 6 methods are in WindowAdapter // and they are set to do nothing }

15 Besides WindowListener/WindowAdapter, Java has lots of Listener/Adapter pairs package java.awt.event ComponentListener/ComponentAdapter ContainerListener/ContainerAdapter FocusListener/FocusAdapter HierarchyBoundsListener/HierarchyBoundsAdapter KeyListener/KeyAdapter MouseListener/MouseAdapter MouseMotionListener/MouseMotionAdapter WindowListener/WindowAdapter package java.awt.dnd DragSourceListener/DragSourceAdapter DragTargetListener/DragTargetAdapter package javax.swing.event InternalFrameListener/InternalFrameAdapter MouseInputListener/MouseInputAdapter

16 Java Data Base Connectivity (JDBC) Adapter Write code in Java using the methods of the JDBC Adapter The Adapter creates SQL commands for you Picture from IBM

17 The Façade Design Pattern

18 Façade is closely related to Adapter 18 Provide a unified interface to a set of interfaces in a System. Façade defines a higher level interface that makes the subsystem easier to use GangOf4 Facade takes a "riddle wrapped in an enigma shrouded in mystery", and interjects a wrapper that tames the amorphous and inscrutable mass of software. SourceMaking

19 A more UML-like view

20 Façade Façade is used to Create a simpler interface Reduce the number of objects that a client deals with Hide or encapsulate a large system Decouples a client from a subsystem of components

21 Example of Façade A CSc 436 student proposal to build a Façade …creating an open source library to introduce people to the power of the OpenCL API. Why? Many people complain about the various intricacies of the "boiler plate" code just to get things working. This library will handle all this for the user so they can focus on learning the techniques of OpenCL. OpenCL™ is the first open, royalty-free standard for cross-platform, parallel programming of modern processors found in personal computers, servers and handheld/embedded devices.

22 Differences between Adapter, Façade Whereas Adapter reuses an old interface, Facade defines a new interface Adapter makes two existing interfaces (a bunch of methods) work together as opposed to defining a new one

23 Flyweight Design Pattern Do we need one tree image or hundreds?

24 Flyweight Design Pattern Do we need 40,621 String objects that equals “University of Arizona”? CSc127A University of Arizona CSC 335

25 Flyweight Design Pattern Could each tile use the same terrain instance?

26 Flyweight Design Pattern Problem: Constructing many objects is a relatively slow operation for a computer to perform and/or it takes CPU time and memory to store objects therefore In large programs we should try to reduce the number of objects we create while the program is running

27 Rumor has it that read will not read the image file if it has already been created File f = new File(“megaman.gif"); BufferedImage sprites =; Rumor has it that read will not read the image file if it has already been created Read is a Flyweight

28 String is a FlyWeight Consider new String, ==, equals, and “a literal” Which assertions pass? String a = "horse"; String b = "horse"; assertTrue(a == b); // Pass? ______ String c = new String("horse"); assertTrue(a == c); // Pass? ______ assertTrue(b == c); // Pass? ______ assertTrue(b.equals(c)); // Pass? ______

29 Code demo Flyweight images so there is only one image for each character to spell G A M E O V E R

30 Flyweights often have a HashMap and check to see if the object exists public class LetterFlyweight implements LetterInterface { private static final HashMap myLetterTable = new HashMap<>(); private final Image myImage; private final char myChar; private LetterFlyweight(Image aLetter, char aChar) { myImage = aLetter; myChar = aChar; } public static LetterFlyweight getLetter(char key) { if (myLetterTable.containsKey(key)) return myLetterTable.get(key); else { String path = key + ".JPG";

Download ppt "3-1 Three Design Patterns: Adapter, Façade, Flyweight C Sc 335 Rick Mercer."

Similar presentations

Ads by Google