Download Proxy, Template Method, Observer, and Decorator Patterns - Prof. Adam A. Porter and more Study notes Programming Languages in PDF only on Docsity!
52
Proxy Pattern Motivation
- Goal:
- Prevent an object from being accessed directly by its clients
- Solution:
- Use an additional object, called a proxy
- Clients access protected object only through proxy
- Proxy keeps track of status and/or location of protected object
Uses of the Proxy Pattern
- Virtual proxy : impose a lazy creation semantics, to
avoid expensive object creations when strictly unnecessary.
- Monitor proxy : impose security constraints on the
original object, say by making some public fields inaccessible.
- Remote proxy : hide the fact that an object resides on a remote location.
54
Proxy Pattern Class Diagram
Object Diagram
58
Structure
Example: JUnit
- Junit uses template methods pattern for run()
package junit.framework; public class TestCase { public void run() { setUp(); runTest(); tearDown() }}
- In the class example, we subclass TestCase and
override setUp() and tearDown()
60
Observer pattern
- Problem
- Objects that depend on a certain subject must be made aware of when that subject changes - E.g. receives an event, changes its local state, etc.
- These objects should not depend on the implementation details of the subject - They just care about how it changes, not how it’s implemented.
Observer pattern
- Solution structure
- Subject is aware of its observers (dependents)
- Observers are notified by the subject when something changes, and respond as necessary
- Abstract subject
- Maintains list of observers; defines a means for notifying them when something happens
- Abstract observer
- Defines the means for notification (update)
64
- Concrete subject: Timestamper (say)
- Notifies observers by calling super.process() whenever it receives an event. Passes information of interest to each observer via the observer’s process() call.
- Concrete observer: EventProcessor subclasses
- Act on events that they receive from process().
Project 1 Event Notification
(almost an observer)
Project 1 Example
Dispatcher Attach(EventProcessor) Detach(EventProcessor) Process(Event)
observers EventProcessor Process(event)
TimeStamper Process(Event)
For all observers o o.process(e);
e’ = munge(e); super.process(e’)
TimeStamper, Dispatcher, Printer, … Process(Event)
66
Design Decisions
- Dispatcher is not an abstract class
- You can create a dispatcher just to forward events, you don’t have to subclass it (though it’s useful to do so)
- Concrete Observers receive the events of interest as arguments to their process() method - Could also have that method call back to the concrete subject to acquire the event
- Subjects and Observers share the same superclass
- Notify and are notified using the same method: process(). Notification happens when event received.
- Could do things differently …
Observer Pattern (from Gang of 4)
This style of observer seeks to keep the state of multiple objects consistent
70
Implementation Issues
- Storing list of observers
- Observing multiple subjects
- typically add parameters to update()
- Who triggers update?
- State-setting operations of subject
- Possibly too many updates
- client
- Error-prone if an observer forgets to send notification message
Implementation Issues (cont’d)
- How much information should subject send with update() messages? - Push model (event notification): subject sends all information that observers may require - Pull model: Subject sends no information
- Registering observers for certain events only
- Have filter objects, like Project 1
- Build notion of filter into Abstract subject; clients include filters when attaching
72
Decorator Pattern
• Motivation
- Want to add responsibilities/capabilities to individual objects, not to an entire class.
- Inheritance requires a compile-time choice of parent class.
• Solution
- Enclose the component in another object that adds the responsibility/capability - The enclosing object is called a decorator.
Decorator Pattern: Example
76
Decorator Pattern Analysis
- Advantages
- fewer classes than with static inheritance
- dynamic addition/removal of decorators
- keeps root classes simple
- Disadvantages
- proliferation of run-time instances
- abstract Decorator must provide common interface
- Tradeoffs:
- useful when components are lightweight
Example 1: Java I/O
FileReader frdr = new FileReader(filename); LineNumberReader lrdr = new LineNumberReader(frdr); String line; while ((line = lrdr.readLine()) != null) { System.out.print(lrdr.getLineNumber() + ":\t" + line); }
78
Interaction diagram
Example 2: Project 1 EventProcessors
EventProcessor process(Event)
Printer process(Event e)
Print(e);
Dispatcher process(Event e)
TimeStamper process(Event e)
Filter process(Event e) Each concrete subclass adds its own special behavior
…
e = mystuff(e) super.process(e)
82
Example – Finite State Machine
class FSM { State state; public FSM(State s) { state = s; } public void move(char c) { state = state.move(c); } public boolean accept() { return state.accept();} }
public interface State { State move(char c); boolean accept(); }
FSM Example – cont.
class State1 implements State { static State1 instance = new State1(); private State1() {} public State move (char c) { switch (c) { case 'a': return State2.instance; case 'b': return State1.instance; default: throw new IllegalArgumentException(); } } public boolean accept() {return false;} }
class State2 implements State { static State2 instance = new State2(); private State2() {} public State move (char c) { switch (c) { case 'a': return State1.instance; case 'b': return State1.instance; default: throw new IllegalArgumentException(); } } public boolean accept() {return true;} }
84
Structure of State pattern
Instance of State Pattern
This document was created with Win2PDF available at http://www.daneprairie.com. The unregistered version of Win2PDF is for evaluation or non-commercial use only.