0% found this document useful (0 votes)
24 views59 pages

Week 9

The document discusses the Law of Demeter principle for reducing coupling between classes. It provides examples of how the principle can be applied and the benefits it provides such as easier analysis and improved maintainability. It also discusses how the Facade pattern can be used to provide a simple interface to a set of classes in a subsystem.

Uploaded by

Vishnu Varma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views59 pages

Week 9

The document discusses the Law of Demeter principle for reducing coupling between classes. It provides examples of how the principle can be applied and the benefits it provides such as easier analysis and improved maintainability. It also discusses how the Facade pattern can be used to provide a simple interface to a set of classes in a subsystem.

Uploaded by

Vishnu Varma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Problem: Law of Demeter

• How to avoid a class from interacting with


indirectly associated objects?

EL
1
Bill * Item ItemSpec
Solution: computeTotal getItemSpec findPrice

PT
• If two classes have no other reason to be
directly aware of each other:
N
– Then the two classes should not directly interact.

1
Collaborators

EL
PT
N
2
Law of Demeter
• In a method, calls should only be made to the
methods of following objects:

EL
– This object (or self)

PT
– An object parameter of the method
– An object attribute of self
N
– An object created within the method

3
A Hypothetical example
class A { class B {
private B b = new B(); C c;

EL
}
public void m() {
class C {

PT
this.b.c.foo(); // High
public void foo() {
coupling: bad
} N }
}
}

4
Law of Demeter: Example
Bill 1 Item ItemSpec
computeTotal * getItemSpec findPrice

EL
Violation: item.getItemspec().findprice()

PT
Bill 1 Item ItemSpec
computeTotal * N
computeSubtotal findPrice

5
• In a class PaperBoy,
LoD Programming Style
– do not use customer.getWallet().getCash(due);
– rather use customer.getPayment(due); and in
customer.getPayment (due), use wallet.getCash(due)

EL
• Benefit:
– Easier analysis

PT
• Tradeoff:
N
– More statements, but simpler statements
• Experiments show significantly improved maintainability.

6
Law of Demeter: Final Analysis
• Reduces coupling between classes

EL
• Adds a small amount of overhead in
the form of indirect method calls

PT
N
7
“The basic effect of applying this Law is the
creation of loosely coupled classes, whose
implementation secrets are encapsulated. Such

EL
classes are fairly unencumbered, meaning that
to understand the working of one class, you

PT
need not understand the details of many other
N
classes.” Grady Booch

8
• Problem: Polymorphism
– How to handle alternative operations based on
subtypes?
• Solution:

EL
– When alternate behaviours are selected based
on the type of an object,

PT
– Use polymorphic method call to select the
behaviour, N
– Rather than using if statement to test the type.

9
Polymorphism Pattern Advantage

• Easily extendible as compared to using


explicit selection logic

EL
PT
N
10
EL
GoF Design Patterns

PT
N
11
• Good designs need to cope with change: What
– Underlying technologies change Problems do
– Business goals change
GoF DPs
solve?
– User expectations change

EL
• How to cope with change?

PT
– Encapsulation
– Inheritance
– Polymorphism
N
12
Types of GoF Patterns
• Creational patterns:
– How objects are created?

EL
• Structural patterns:
– How classes or objects are composed into

PT
larger groups?
N
• Behavioral patterns:
– How responsibility is distributed?

13
• Structural Patterns GoF Pattern Taxonomy
– Adapters, Bridges, Facades, and Proxies are variations of a single
theme:
• Reduce the coupling between two or more classes
• Introduce abstract classes to enable future extensions
• Encapsulate complex structures

EL
• Behavioral Patterns
– Assignment of responsibilities between objects: Who does what?

PT
– Behaviorial patterns concern cohesion and coupling.
• Creational Patterns
– The goal is to provide a simple abstraction for a complex instantiation
process. N
– Make the system independent from the way its objects are created,
composed and represented.

14
Taxonomy of
GoF Patterns
(23 Patterns)

EL
PT
N
15
Problem: How to access a large number of classes Facade
(having complex internal interactions) in a Pattern
package?

EL
• Context: A package is a cohesive set of classes:
– Example: RDBMS interface package

PT
DBMSP
• Solution: Create a facade class (e.g. DBfacade) d
N
to provide a common interface to the services of
the package.

16
R1 R2 R3 R1 R2 R3 Facade
Service Service
Package Package

S1 S2 S1 S2

EL
Facade
S3 S4 S3 S4

PT
R4 R5 N
(a) Service invocation without
R4 R5
(b) Service invocation using a
a façade façade class

17
Before and
DBQ Client A Client B After Using
Client A Facade

Database

EL
DBW Facade

PT
Client B
DBR DBQ DBW DBR

Before
N After
Facade Facade

18
Facade Structure
Package
Facade

EL
Cl C2 C3

PT
C5
C4 N C6 C7

19
Compiler
Compile() Facade
Scanner Token Pattern:
CodeGenerator Parser Example
ProgNodeBuilder

EL
RISCCG
ProgNode
StackMachineCG

PT
Statement Node
N Expression Node

Compiler Subsystem Classes Variable Node

20
Bank Façade:
AccountService
Bank
Example
createAccount(…)
deposit(…)
withdraw(…)

EL
BankFaçade

createAccount(…) TransactionService

PT
deposit(…) addTransaction(…)
withdraw(…)
addTransaction(…)
applyForLoan(…) N LoanService

applyForLoan(…)


21
public class BankFaçade { public withdraw(int accountId, float
amount) {
Façade
private AccountService
accountService;
accountService.withdraw(accou Code:
private TransactionService
ntId, amount); Bank
transactionService; } Example
private LoanService loanService; public addTransaction(Transaction

EL
public addAccount(Account account) { tx) {
transactionService.addTransac
tion(tx);
accountService.addAccount(account);

PT
} }
public deposit(int accountId, float public applyForLoan(Customer cust,
amount) { LoanDetails loan) {

N
accountService.deposit(accountId,
amount);
}
loanService.apply(cust, loan);

}
}

22
• Clients communicate with the subsystem by Discussions
on Façade
sending requests to Façade:
Pattern
– Façade forwards them to the appropriate

EL
subsystem object(s).
– Promotes low coupling; clients know only about

PT
the Façade.

N
• Often, does little more than just delegating
requests to other classes inside the package!

23
• Although subsystem objects perform actual
Discussions
work: on Façade
– Façade may have to translate between Pattern

EL
subsystem interfaces.

• Clients that use the Façade:

PT
– Don’t have to access its subsystem objects
directly. N
24
• Problem: Observer Pattern
– When a model object changes state asynchronously
and is accessed by several view objects:

EL
• How should the interactions between the model
and the view objects be structured?

PT
• Solution: Define a one-to-many dependency, so
N
that when model changes state, all of its dependents
are notified and updated automatically.

25
Observer Pattern --- Background
• Symptom of Poorly designed GUIs:
– Classes with a large and incoherent set of
responsibilities:

EL
– Encompass: GUI, Listening to events, domain logic,
application logic, etc...

PT
• We should separate the concerns.
N
– Model and view objects
– But, how should they communicate?

26
Model vs. View Objects
Subject or Model
Subject
XML Interface
xyz…

EL
PT
Observers

Web PDA Cell Terminal


Browser Phone

N
View objects

27
• Model objects should not invoke Model View
Separation Patterns:
services of view objects. Solution Overview
– Vice-versa is OK

EL
– View objects are transient

PT
– Reuse, extension, maintenance are frequent.
– A change to a view object should not require
N
change to the model object.

28
• Most obvious solution: Solution 1: Pull from Above

– View (boundary) objects invoke model objects.


Subject or Model

• Problem:

EL
Subject
XML Interface

xyz…

– Views can become inconsistent

PT
Web PDA Cell Terminal
Browser Phone

– View object does not know when


N
model state changes

29
Context in Which Pull from Above Does Not Work
• Data changes asynchronously
– An event in a simulation experiment,

EL
stock market alert, network monitor, etc.

PT
– A mouse event causes change to a shape.
N
• Dynamic set of observers

30
Observer Pattern: Context
• There could be many observers
– Also the number of observers may vary
dynamically

EL
– Each observer may react differently to the same
notification

PT
• Subject (model) should be as much decoupled
N
from the observers as possible:
– Allow observers to change independently of the subject

31
Observer -- Non
software example
When an object

15 changes its state,


all its dependants

EL
are notified.

PT
N
32
Example: Stock
Real time Quote Service
Market Data
Feed Stock
market

EL
Stock Quotes
A

PT
A
A B D
Customer C Customer
C
Customer N
Customer Customer

Observers

33
Observer Pattern: Main Idea
• When observable (model) changes state:
– All dependent objects are notified ---

EL
these objects update themselves.

PT
– Allows for consistency between related
objects without tightly coupling the
classes.
N
34
Observer Pattern: Solution
• Observers should register themselves with the
model object.
– The model object maintains a list of the registered

EL
observers.
• When a change occurs to a model object:

PT
– Model notifies all registered observers.
– Subsequently, each observer queries the model
N
object to get any specific information about the
changes.

35
• Subject Interface
Key Players
– Provides interface for attaching/ detaching subjects
• Observer Interface

– Defines an interface for notifying the subjects of

EL
changes to the object.
• ConcreteSubject

PT
– Implements subject interface to send notification to
observers when state changes
• ConcreteObserver
N
– Implements Observer interface to keep state consistent
with subject

36
<<Interface>>
Subject
<<Interface>>
Observer
Structure of
informs
Observer
+notify()
+attach(Observer)
+update( ) Pattern
for all observer obs +detach( Observer)
{
obs.update();
}

EL
PT
Concrete Subject Concrete Observer
queries
-subjectState
+update( )

return subjectState
+getState()
+setState() N observerState = subject.getState();

37
Observer
• Defines a one-to-many dependency between Pattern
objects:
– When one object changes state, all its dependents
are notified and updated automatically.

EL
• Used to decouple the subject from the

PT
observer:
– Since the subject has little information about needs
of the observer. N
– Can result in excessive notifications.

38
Working of Observer Pattern
 ConcreteSubject notifies its observers:
oWhenever a change makes its state

EL
inconsistent with the observers.

PT
• After being informed of change:

N
– A ConcreteObserver queries the subject to
reconcile its state with subjects.

39
aFile anInfoView aListView Observer:
Attach()
Sequence
diagram
Attach()

EL
notify()

PT
update()
update()

getState()
“foo”
N
40
Activities of
• ConcreteObserver.Update(): Update
– Repaint a user interface

EL
– Check for exceeding thresholds, etc.

PT
– These are operations that might clutter
up a domain class (Subject).
N
41
Observer Java Implementation
• A Subject class usually maintains:
– An ArrayList of ids of the registered

EL
Observers

PT
– Makes it easier when a random object
N
wants to attach or detach

42
public interface Observer { Observer Pattern Java
Implementation
public void update(Subject o );
Subject *
attach(observer) observers
Observer

} detach(observer)
notify()
update()

EL
Public interface Subject {
subject
ConcreteObserver
ConcreteSubject
update()
getState()
setState(newState)
public void addObserver(Observer o); subjectState observerState

PT
public void removeObserver(Observer o);
public String getState();
N
public void setState(String state);
}

43
Subject
* Observer
attach(Observer)
detach(Observer)
Update()
notify()
for all o in
observers {

EL
o.update( ) }

ConcreteObserver
ConcreteSubject

PT
* observerState
subjectState() update()
getState()
setState()

N
return
subjectState
observerState =
subject.getState( )

44
class ConcreteObserver implements Observer {
private String state = "";
public void update(Subject o) {
state = o.getState();
System.out.println("Update received from Subject, state chnged to : " + state);}
}

EL
class ConcreteSubject implements Subject {
private List observers = new ArrayList();
private String state = "";

PT
public String getState() {
return state;}

N
public void setState(String state) {
this.state = state;
notifyObservers();}

45
public void addObserver(Observer o) {
observers.add(o);}

public void removeObserver(Observer o) {


observers.remove(o);}

EL
public void notifyObservers() {
Iterator i = observers.iterator();

PT
while (i.hasNext()) {
Observer o = (Observer) i.next();
o.update(this);}
} N
46
Inbuilt Java Observers
interface Observer {
void update(Observable o, Object arg);
} //java.util.Observer

EL
class Observable {

PT
void addObserver(Observer o) { … }
void deleteObserver(Observer o) { … }

N
void notifyObservers(Object arg) { … }
} //java.util.Observable base-class

47
Java Observer/Observable
• Observers register with Observable
• Observable recognizes events and calls specified method
of observers

EL
• Java Observer

PT
– Interface class, implemented by observers
• Java Observable N
– Class, extended by concrete Observable

48
• Implementers must have an update() method
which the Observable object x will call Java Observer
Class
– update(Observable x, Object y)

EL
• When Observable object x calls the update()

PT
method for a registered observer:

N
– It passes itself as an identifier and also a data
object y

49
Java Observable Class
• Extended by concrete Observables

• Inherited methods from Observable

EL
– addObserver(Observer z)
• Adds the object z to the observable’s list of observers

PT
– notifyObserver(Object y)
N
• Calls the update() method for each observer in its list of
observers, passing y as the data object

50
Java Support for Observer Pattern
interface Observer {

void update (Observable sub, Object arg)


}
Subject.

EL
class Observable {
public void addObserver(Observer o) {}

PT
public void deleteObserver (Observer o) {}
public void notifyObservers(Object arg) {}

… N
public boolean hasChanged() {}

51
Observer Pattern- Implementation Example 1
public PiChartView implements Observer {
void update(Observable sub, Object arg) {
// repaint the pi-chart
} } A Concrete Observer.

EL
class StatsTable extends Observable{

PT
public notify() {

} N
}

52
Observer Pattern - Consequences
• Abstract coupling between subject and observer:
–subject need not know the concrete observers

EL
• Support for broadcast communication:
–All observers are notified

PT
• Supports asynchronous updates:
N
–Observers need not know when updates occur

53
• Consequences
+ Modularity: subject and observers may vary independently
+ Extensibility: can define and add any number of observers

EL
+ Customizability: different observers provide different views
of subject

PT
• Implementation Issues
N
– Dangling references
– Registering modifications of interest explicitly

54
Limitations of Observer Pattern
• Model objects incur substantial overhead:
– To support registration of the observers,

EL
– To respond to queries from observers.

PT
• Performance concerns:
N
– Especially when the number of observers is large.

55
Observer Pattern: Final Words
• Indications:
– Asynchronous update of model elements

EL
– Observer and model states need to be

PT
consistent all the time

N
– Number of observers can change dynamically

56
Observer: Final Words
• Contra-Indications:

EL
– Static data

PT
– Fixed viewers
N
57
Java Observer Deprecated!
• They don't provide a rich enough event model for
applications!
– For example, they support only the notion that something has

EL
changed, but they don't convey any information about what
has changed

PT
• Not threadsafe!
N
• Make use of PropertyChangeListener instead:
– Which itself is an implementation of Observer pattern

58
Home Work
• Provide class design for:
• Blog application: Any one can enrol by providing
e-mail. Any blog posted is communicated to the

EL
registered users.

PT
• Cricket application: Any one can enrol by
providing e-mail. Any development (runs, out,
N
over etc) posted is communicated to the
registered users.

59

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy