Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Fundamentals Design Patterns Delegation Interface Immutable Marker Interface Proxy 10/14/2001 8:35 PM."— Presentation transcript:

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

2 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

3 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

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

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

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

7 FDP - Delegation - Example // Instance of this class represent a flight segment. class FlightSegment { LuggageCompartment luggage; /** * Check a piece of luggage * @param piece The piece of luggage to be checked. * @exception 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

8 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

9 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

10 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

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

12 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

13 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

14 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

15 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

16 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

17 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

18 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 // @param x The x position associationed with this object. // @param 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

19 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. // @param xOffset The x offset. // @param 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

20 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

21 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

22 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

23 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.

24 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

25 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

26 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

27 // 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. // @return true if enumeration contains more elements; public boolean hasMoreElements() { return thisNode != null; } // hasMoreElements() FDP - Marker Interface - Example 10/14/2001 8:35 PM

28 * Returns the next element of this enumeration. * @return the next element of this enumeration. * @exception 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

29 /** * 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. * @params target The object to search for. * @return 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

30 /** * Find an object in a linked list that is equal to the given object (using ==operator) * @params target The object to search for. * @return 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

31 /** Find an object in a linked list that is equal to the given object (using equal method) * @params target The object to search for. * @return 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

32 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

33 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

34 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

35 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

36 FDP - Proxy - Example /** Construct an empty hashtable. * @param initialCapacity the initial capacity of the hashtable. * @param loadFactor a number between 0.0 and 1.0. * @exception 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. * @param initialCapacity the initial capacity of the hashtable. * @exception IllegalArgumentException if initialCapacity <=0 */ public LargeHashtable(int initialCapacity) { theHashTable = new ReferenceCountedHashTable(initialCapacity); } // constructor(int) 10/14/2001 8:35 PM

37 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

38 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. * @param value The value to search for. * @exception 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. * @param key The key to search for. public synchronized boolean containsKey(Object key) { return theHashTable.containsKey(key); } // containsKey(Object) 10/14/2001 8:35 PM

39 FDP - Proxy - Example // Return the value associated with the specified key in this Hashtable. * @param 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. * @param key the key. * @param value the value. * @return previous value of key in hashtable, or null if it did not have one. * @exception 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

40 FDP - Proxy - Example // Remove the key-value pair with given key from this Hashtable.@param 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

41 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

42 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. * @param initialCapacity the initial capacity of the hashtable. * @param loadFactor a number between 0.0 and 1.0. * @exception 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

43 FDP - Proxy - Example /** * Construct an empty hashtable. * @param initialCapacity the initial capacity of the hashtable. * @exception 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

44 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


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

Similar presentations


Ads by Google