Fundamentals Design Patterns Delegation Interface Immutable Marker Interface Proxy 10/14/2001 8:35 PM.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
queues1 Queues Data structures that wait their turn.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Dictionaries Chapter Chapter Contents Specifications for the ADT Dictionary Entries and methods Using the ADT Dictionary English Dictionary Telephone.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Using Maps. A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable,
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
HASHING CSC 172 SPRING 2002 LECTURE 22. Hashing A cool way to get from an element x to the place where x can be found An array [0..B-1] of buckets Bucket.
CHAPTER 3 COLLECTIONS SET Collection. 2 Abstract Data Types A data type consists of a set of values or elements, called its domain, and a set of operators.
Iterators Chapter 7. Chapter Contents What is an Iterator? A Basic Iterator Visits every item in a collection Knows if it has visited all items Doesn’t.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Chapter 10 Classes Continued
Using Maps. 2 A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable,
Stacks, Queues, and Deques
Proxy Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Chapter 3 Introduction to Collections – Stacks Modified
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
In the name of Allah The Proxy Pattern Elham moazzen.
Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt * Object-Oriented Software Development Unit 8.
Partitioning Patterns How to partition complex actors and concepts into multiple classes. Layered Initialization Filter Composite.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
RED-BLACK TREE SEARCH THE FOLLOWING METHOD IS IN TreeMap.java:
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Design Patterns Definition:
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
Sets and Maps Computer Science 4 Mr. Gerb Reference: Objective: Understand the two basic applications of searching.
A Introduction to Computing II Lecture 11: Hashtables Fall Session 2000.
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Confinement.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Collections Dwight Deugo Nesa Matic
C19: Collection Classes (don’t forget to look at all the online code examples)
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered.
1 Chapter 4 Unordered List. 2 Learning Objectives ● Describe the properties of an unordered list. ● Study sequential search and analyze its worst- case.
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
EECE 310: Software Engineering
Methods Attributes Method Modifiers ‘static’
CS313D: Advanced Programming Language
Using Maps.
Compiler Design 18. Object Oriented Semantic Analysis (Symbol Tables, Type Checking) Kanat Bolazar March 30, 2010.
Polymorphism and access control
Using Maps.
Programming II (CS300) Chapter 07: Linked Lists and Iterators
Computer Science and Engineering
L5. Necessary Java Programming Techniques
Chapter 8 Class Inheritance and Interfaces
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Hashing in java.util
Presentation transcript:

Fundamentals Design Patterns Delegation Interface Immutable Marker Interface Proxy 10/14/2001 8:35 PM

FDP - Delegation Synopsis: Delegation is a fundamental method to extend and reuse a classes functionality ( behavior or methods) Context: Allows instances of a class to play multiple roles. Forces: An object needs to play multiple roles in a subclass relationship or wishes to reuse specific behavior. 10/14/2001 8:35 PM

FDP - Delegation Solution: Reuse and extend behavior using delegation Consequences: Not well structured in use. Proliferation of indirect delegation Must be disciplines in use. 10/14/2001 8:35 PM

FDP - Delegation class x public void methodforx () { } class y x _x = new x(); …… _x.methodforx ( ) DELEGATION 10/14/2001 8:35 PM

FDP - Delegation - Example DelegatorDelegatee uses1 1 10/14/2001 8:35 PM

FDP - Delegation - Example FlightSegmentLuggageCompartment 1.1 checkluggage() checkluggage() Instance 10/14/2001 8:35 PM

FDP - Delegation - Example // Instance of this class represent a flight segment. class FlightSegment { LuggageCompartment luggage; /** * Check a piece of luggage piece The piece of luggage to be checked. LuggageException if piece cannot be checked. */ void checkLuggage(Luggage piece) throws LuggageException { luggage.checkLuggage(piece); } // checkLuggage(Luggage) } // class FlightSegment DELEGATION 10/14/2001 8:35 PM

FDP - Interface Synopsis: Keep a class, class A, that uses data and services provided by instances of other classes, classes B,C,…., independent of those classes by having it, class A, access those instances, of classes B,C, …, through an interface Context: You need to reuse a information structure and/or behavior by many other similar classes. 10/14/2001 8:35 PM

Forces: If the instances of a class must use another object and that object is assumed to belong to a particular class, then the reusability of the class is compromised. Instances of a class use other objects and all they require is implementation of particular methods. Use of an interface limits the dependency of the classes. FDP - Interface 10/14/2001 8:35 PM

FDP - Interface Solution: Use a class indirectly and avoid tight coupling. Consequences: Keeps the functionality from another class Decreases understandability. 10/14/2001 8:35 PM

FDP - Interface - Example AddressPanelAddressIF uses 1 1 DataClass Inheritance 10/14/2001 8:35 PM

FDP - Interface - Example // Classes that contain editable street address information implement * this interface. public interface AddressIF { public String getAddress1(); // Get the first line of the street address. public void setAddress1(String address1); // Set the first line of the street address. public String getAddress2(); // Get the second line of the street address. public void setAddress2(String address2); // Set the second line of the street address. public String getCity(); // Get the city. public void setCity(String city); // Set the city. public String getState(); // Get the state. public void setState(String state); // Set the state. public String getPostalCode() ; // get the postal code public void setPostalCode(String PostalCode); // set the postal code } // interface AddressIF 10/14/2001 8:35 PM

class Facility { private String facilityName; private String costCenterID; public String getFacilityName() { // Return the facility name return facilityName; } // getFacilityName() public String getCostCenterID() { // Return the costCenterID return costCenterID; } // getCostCenterID() } // class Facility FDP - Interface - Example 10/14/2001 8:35 PM

class ReceivingLocation extends Facility implements AddressIF{ private String address1; private String address2; private String city; private String state; private String postalCode; FDP - Interface - Example 10/14/2001 8:35 PM

public String getAddress1() { return address1; } // Get the first line of the street address. public void setAddress1(String address1) { this.address1 = address1; } // Set first line public String getAddress2() { return address2; } // Get the second line of the street address. public void setAddress2(String address2) { this.address2 = address2; } // Set second line public String getCity() { return city; } // Get the city. public void setCity(String city) { this.city = city; } // Set the city. public String getState() { return state; } // Get the state. public void setState(String state) { this.state = state; } // Set the state. public String getPostalCode() { return postalCode; } // get the postal code public void setPostalCode(String postalCode) { // set the postal code this.postalCode = postalCode; } // setPostalCode(String) } // class ReceivingLocation FDP - Interface - Example 10/14/2001 8:35 PM

FDP - Immutable Synopsis: Increases robustness of objects that share references to the same object. Forbids state information to change after object created. Context: Allows multiple objects to share access to same object. No methods to modify its own value. 10/14/2001 8:35 PM

FDP - Immutable Forces: You need objects that are passive. Allows synchronization of information embedded in threads. Solution: Make shared objects immutable (unchangable) disallowing any changes to their state. Consequences: Increases memory overhead. 10/14/2001 8:35 PM

FDP - Immutable - Example // Instances of this class represent a position on a playing field. // Lack of methods to set x and y value is not an oversight. // Instances of this class are intended to be immutable. class Position { private int x; private int y; // Constructor x The x position associationed with this object. y The y position associationed with this object. public Position(int x, int y) { this.x = x; this.y = y; } // Position(int, int) 10/14/2001 8:35 PM

public int getX() { return x; } // Return the x value associated with this object. public int getY() { return y; } // Return the y value assolciated with this object. // Return a Position object that has x and y values that are // offset from the x and y values of this object by the given // amount. xOffset The x offset. yOffset The y offset. public Position offset(int xOffset, int yOffset) { return new Position(x+xOffset, y+yOffset); } // offset(int, int) } // classs Position FDP - Immutable - Example 10/14/2001 8:35 PM

FDP - Marker Interface Synopsis: Uses interfaces that declare no methods or variables to indicate semantic attributes of a class. Mainly used in utility classes Context: Allows identification of an interface that does not declare methods or variables. 10/14/2001 8:35 PM

FDP - Marker Interface Forces: Utility classes need to know use without relying on object being an instance of a particular class. Solution: Declare that a class implements a marker interface to indicate that it belongs to the classification associated with the marker interface. Consequences: Transparency relationship between utility class and marker interface. 10/14/2001 8:35 PM

FDP - Marker Interface - Example /** Classes that implement this interface can be compared for equality by the == operator */ public interface EqualByIdentity { } 10/14/2001 8:35 PM

FDP - Marker Interface - Example UtilityMarkerIF recognizes 1 1 Marked Inheritance 10/14/2001 8:35 PM Instances of the utility classes are able to make inferences about objects passed to their methods without depending on the objects to be instances of any particular class.

import java.util.Enumeration; import java.util.NoSuchElementException; // Instances of this class are nodes of a linked list. // Linked list - chain of objects that have two object references // One is the head, another data object. // The other is tail of the list, either null or another linked list. public class LinkedList implements Cloneable, java.io.Serializable { private Object head; private LinkedList tail; private boolean traversed = false; // true when this node is being traversed FDP - Marker Interface - Example 10/14/2001 8:35 PM

public LinkedList() {// Creates a LinkedList with a null head and null tail. this(null, null); } // constructor() public LinkedList(Object head) {//Creates LinkedList with given head & null tail this(head, null); } // constructor(LinkedList) // Creates LinkedList with given head and tail which is the remaining linked list public LinkedList(Object head, LinkedList tail) { this.head = head; this.tail = tail; } // constructor(LinkedList) FDP - Marker Interface - Example 10/14/2001 8:35 PM

public Object getHead() { return head; } // getHead() // Return head of linked list. public LinkedList getTail() {return tail; } // getTail() // Return tail of linked list. synchronized public int size() { // Return the number of nodes in linked list if (tail == null) return 1; try { traversed = true; if (tail.traversed) return 1; return 1 + tail.size(); } finally { traversed = false; } // try } // size() FDP - Marker Interface - Example 10/14/2001 8:35 PM

// Return an Enumeration of the data in this linked list (the heads). public Enumeration elements() { return new ListEnumeration(); } // elements() // private class to enumerate data of a linked list. private class ListEnumeration implements Enumeration { private LinkedList thisNode = LinkedList.this; // Tests if this enumeration contains more elements. true if enumeration contains more elements; public boolean hasMoreElements() { return thisNode != null; } // hasMoreElements() FDP - Marker Interface - Example 10/14/2001 8:35 PM

* Returns the next element of this enumeration. the next element of this enumeration. NoSuchElementException if no more elements exist. */ public Object nextElement() { if (thisNode == null) throw new NoSuchElementException(); Object next = thisNode.head; thisNode = thisNode.tail; return next; } // nextElement() } // class ListEnumeration FDP - Marker Interface - Example 10/14/2001 8:35 PM

/** * Find an object in linked list equal to the given object (using object equal method) * However, if the given object implements the EqualByIdentity interface, * then equality will be determined by the == operator. target The object to search for. a LinkedList whose head is equal to the given object or * null if the target is not found. */ public LinkedList find(Object target) { if (target == null || target instanceof EqualByIdentity) return findEq(target); else return findEquals(target); } // find(Object) FDP - Marker Interface - Example 10/14/2001 8:35 PM

/** * Find an object in a linked list that is equal to the given object (using ==operator) target The object to search for. a LinkedList whose head is equal to the given object. */ private synchronized LinkedList findEq(Object target) { if (head == target) return this; if (tail == null) return null; try { traversed = true; if (tail.traversed) return null; return tail.findEq(target); } finally { traversed = false; } // try } // find(Object) FDP - Marker Interface - Example 10/14/2001 8:35 PM

/** Find an object in a linked list that is equal to the given object (using equal method) target The object to search for. a LinkedList whose head is equal to the given object. */ private synchronized LinkedList findEquals(Object target) { if (head.equals(target)) return this; if (tail == null) return null; try { traversed = true; if (tail.traversed) return null; return tail.findEquals(target); } finally { traversed = false; } // try } // find(Object) } // class LinkedList FDP - Marker Interface - Example 10/14/2001 8:35 PM

FDP - Proxy Synopsis: General pattern occuring in many other patterns but never by itself in pure form. It forces method calls to an object to occur indirectly through a proxy object that acts as a surrogate for the other object, delegating method calls to that object. Context: Proxy object receives method calls on behalf of another object. 10/14/2001 8:35 PM

FDP - Proxy Forces: Provide services (methods) in a way transparent to classes using those services. Solution: Proxy object and the service providing object must either be instances of a common super class or implement a common interface. Consequences: Could introduce new failure points. 10/14/2001 8:35 PM

FDP - Proxy - Example import java.util.Enumeration; import java.util.Hashtable; /** * This subclass of Hashtable is functionally equivalent to Hashtable except in the clone operation. * * A common reason for cloning is to avoid holding a lock on the object In a multi-threaded program * You want to lock the hash table if you are updating it but not just to use it for searching * When you fetch a value out of the hashtable is to have exclusive access to the Hashtable. * While that is going on, other threads wait to gain access to the same Hashtable, * If other threads comes along and changes Hastable contents in which you are fetching values, * then you may get some inconsittent results. * cloning the Hashtable avoids that problem since the hashtable you are reading from is a copy * If, after you clone a hashtable, there is no subsequent modification to Hashtable, then clone is wasted. * 10/14/2001 8:35 PM

FDP - Proxy - Example * Instances of this class are a copy-on-write proxy for a Hashtable object. * When a proxy's clone method is called, it returns a copy of the proxy but does not copy hastable object. * At that point both the original and the copy of the proxy refer to the same Hashtablec object. * When the proxies are asked to modify the Hashtable, they know they are using a shared Hashtable. * They know they are working with a shared Hashtable object since the Hashtable object is an instance * of a private subclass of Hashtable called ReferenceCountedHashTable. * The ReferenceCountedHashTable keeps a count of how many proxies refer to it. */ public class LargeHashtable extends Hashtable { // The ReferenceCountedHashTable that this is a proxy for. private ReferenceCountedHashTable theHashTable; 10/14/2001 8:35 PM

FDP - Proxy - Example /** Construct an empty hashtable. initialCapacity the initial capacity of the hashtable. loadFactor a number between 0.0 and 1.0. IllegalArgumentException if initialCapacity <=0 or loadFactor <= 0 */ public LargeHashtable(int initialCapacity, float loadFactor) { theHashTable = new ReferenceCountedHashTable(initialCapacity, loadFactor); } // constructor(int, float) /** * Construct an empty hashtable. initialCapacity the initial capacity of the hashtable. IllegalArgumentException if initialCapacity <=0 */ public LargeHashtable(int initialCapacity) { theHashTable = new ReferenceCountedHashTable(initialCapacity); } // constructor(int) 10/14/2001 8:35 PM

FDP - Proxy - Example public LargeHashtable() { // Construct an empty hashtable with a default capacity and load factor. theHashTable = new ReferenceCountedHashTable(); } // constructor() public int size() {return theHashTable.size(); } // size() // Return number of key-value pairs in hashtable. // Return true if Hashtable contains no key-value pairs. public boolean isEmpty() { return theHashTable.isEmpty(); } // isEmpty() // Return an enumeration of the keys in this Hashtable. public synchronized Enumeration keys() { return theHashTable.keys(); } // keys() // Return an enumeration of the values in this Hashtable. public synchronized Enumeration elements() { return theHashTable.elements(); } 10/14/2001 8:35 PM

FDP - Proxy - Example /** * Return true if the given value is part of a key-value pair in this Hashtable * This operation is more expensive and requires a linear search. value The value to search for. NullPointerException if the value is null. */ public synchronized boolean contains(Object value) { return theHashTable.contains(value); } // contains(Object) // Return true if the given key is in this hashtable. key The key to search for. public synchronized boolean containsKey(Object key) { return theHashTable.containsKey(key); } // containsKey(Object) 10/14/2001 8:35 PM

FDP - Proxy - Example // Return the value associated with the specified key in this Hashtable. a key in hashtable. public synchronized Object get(Object key) { return theHashTable.get(key); } // get(key) /** * Add the given key-value pair to this Hashtable. key the key. value the value. previous value of key in hashtable, or null if it did not have one. NullPointerException if the key or value is null. */ public synchronized Object put(Object key, Object value) { copyOnWrite(); return theHashTable.put(key, value); } // put(key, value) 10/14/2001 8:35 PM

FDP - Proxy - Example // Remove the key-value pair with given key from this key that needs to be removed. public synchronized Object remove(Object key) { copyOnWrite(); return theHashTable.remove(key); } // remove(Object) // Remove all key-value pairs from this Hashtable. public synchronized void clear() { copyOnWrite(); theHashTable.clear(); } // clear() // Return a copy of this proxy that accesses the same Hashtable as this proxy. // First to modify contents of Hashtable results in proxy accessing a modified clone of original Hashtable. public synchronized Object clone() { Object copy = super.clone(); theHashTable.addProxy(); return copy; } // clone() 10/14/2001 8:35 PM

FDP - Proxy - Example // Method called before modifying underlying Hashtable. If it is shared then method clones it. private void copyOnWrite() { if (theHashTable.getProxyCount() > 1) { // Synchronize on the original Hashtable to allow consistent recovery on error. synchronized (theHashTable) { theHashTable.removeProxy(); try { theHashTable = (ReferenceCountedHashTable)theHashTable.clone(); } catch (Throwable e) { theHashTable.addProxy(); } // try } // synchronized } // if proxyCount } // copyOnWrite() 10/14/2001 8:35 PM

FDP - Proxy - Example // Return string representation of this Hashtable. public synchronized String toString() {return theHashTable.toString(); } private class ReferenceCountedHashTable extends Hashtable { private int proxyCount = 1; /** * Construct an empty hashtable. initialCapacity the initial capacity of the hashtable. loadFactor a number between 0.0 and 1.0. IllegalArgumentException if initialCapacity <=0 or loadFactor <= 0 */ public ReferenceCountedHashTable(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } // constructor(int, float) 10/14/2001 8:35 PM

FDP - Proxy - Example /** * Construct an empty hashtable. initialCapacity the initial capacity of the hashtable. IllegalArgumentException if initialCapacity <=0 */ public ReferenceCountedHashTable(int initialCapacity) { super(initialCapacity); } // constructor(int) // Construct an empty hashtable with default capacity and load factor. public ReferenceCountedHashTable() { super(); } // constructor() // Return a copy of this object with proxyCount set back to 1. public synchronized Object clone() { ReferenceCountedHashTable copy; copy = (ReferenceCountedHashTable)super.clone(); copy.proxyCount = 1; return copy; } // clone() 10/14/2001 8:35 PM

FDP - Proxy - Example // Return the number of proxies using this object. synchronized int getProxyCount() { return proxyCount; } // getProxyCount() // Increment the number of proxies using this object by one. synchronized void addProxy() { proxyCount++; } // addProxy() // Decrement the number of proxies using this object by one. synchronized void removeProxy() { proxyCount--; } // removeProxy() } // class ReferenceCountedHashTable } // class LargeHashtable 10/14/2001 8:35 PM