0% found this document useful (0 votes)
12 views20 pages

5.1.1 Design Pattern and Observer Pattern - FZN

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)
12 views20 pages

5.1.1 Design Pattern and Observer Pattern - FZN

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/ 20

Design Pattern

● Design patterns represent the best practices used by experienced


object-oriented software developers.
● Design patterns are solutions to general problems that software
developers faced during software development.
● These solutions were obtained by trial and error by numerous
software developers over quite a substantial period of time.
What is Gang of Four (GOF)?

In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John
Vlissides published a book titled Design Patterns - Elements of Reusable
Object-Oriented Software which initiated the concept of Design Pattern in
Software development.
These authors are collectively known as Gang of Four (GOF). According to these
authors design patterns are primarily based on the following principles of object
orientated design.
● Program to an interface not an implementation
● Favor object composition over inheritance
Usage of Design Pattern

Design Patterns have two main usages in software development.

Common platform for developers


Design patterns provide a standard terminology and are specific to particular scenario. For
example, a singleton design pattern signifies use of single object so all developers familiar with
single design pattern will make use of single object and they can tell each other that program is
following a singleton pattern.

Best Practices
Design patterns have been evolved over a long period of time and they provide best solutions to
certain problems faced during software development. Learning these patterns helps inexperienced
developers to learn software design in an easy and faster way.
Types of Design Patterns

As per the design pattern reference book Design Patterns -


Elements of Reusable Object-Oriented Software ,
there are 23 design patterns which can be classified in three categories: Creational,
Structural and Behavioral patterns.
We'll also discuss another category of design pattern: J2EE design patterns.
Creational

- Talks about object creations.


- To make design more readable and less complexity.
- Talks about efficiently object creation.
Structural

- Talks about how classes and objects can be composed.


- Parents-child relationship like inheritance, extend.
- Deals with simplicity in identifying relationships.
Behavioral

- Deals with interactions and responsibility of objects.


- Deals with static, private, protected.
Types of Patterns
Pattern & Description

Creational Patterns

These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects
directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given
use case.

Structural Patterns

These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and
define ways to compose objects to obtain new functionalities.
Behavioral Patterns

These design patterns are specifically concerned with communication between objects.

J2EE Patterns

These design patterns are specifically concerned with the presentation tier. These patterns are identified by Sun Java
Center.
Observer Pattern
Intent: Define a one-to-many dependency between objects so that when one object
change state, all its dependents are notified and updated automatically.
Student-Teacher Example
Class Teacher:
def __init__(self,name): teacher1 = Teacher(“aaa”)
student1= Student(“bbb”)
self.students=[]
self.name=name
student1.add_teacher(teacher1 )
def attach_student(self, student):
self.students.append(student)
print(f"Student {student} added to teacher's list.")
Class Student:
def__init__(self,name): Output:
self.teachers=[] Teacher aaa added to student's list.
def add_teachers(self,teacher): Student bbb added to teacher's list.
self.teachers.append(teacher)
print(f"Teacher {teacher} added to student's list.")
teacher.attach_student(self)
Fan-Celebrity Example
# Subject (Celebrity) # Observer (Fan)
celebrity = Celebrity()
class Celebrity: class Fan:
fan = Fan()
def __init__(self): def __init__(self):
#fan starts following…
self._fans = [] self._celebrities = []
fan.add_celebrity(celebrity)
def update(self, celebrity):
self._state = None #celeb changes status and
state = celebrity.get_state()
def attach(self, fan): #notification is received by fan.
def add_celebrity(self, celebrity):
self._fans.append(fan) celebrity.set_state('New state')
self._celebrities.append(celebrity)
def detach(self, fan): #fan can stop following…
celebrity.attach(self)
fan.remove_celebrity(celebrity)
self._fans.remove(fan) def remove_celebrity(self, celebrity):
def _notify(self): self._celebrities.remove(celebrity)
for fan in self._fans: celebrity.detach(self)
fan.update(self)
def set_state(self, state):
self._state = state
self._notify()
def get_state(self):
return self._state
Observer Pattern 13

public class Celebrity{


private List<Fan> fans = new ArrayList<Fan>();
private int state;
void attach(Fan f){
fans.add(f);
}
void remove(Fan f){
fans.remove(f);
}
Celebrity class may look like
void notify(){
foreach( Fan f: fans)
this.
f.update(this);
}
void setState(int newState){
state = newState;
notify();
}
int getState(){
return state;
}

}
Observer Pattern 14

public class Celebrity{


private List<Fan> fans = new ArrayList<Fan>();
private int state;
void attach(Fan f){
fans.add(f);
}
void remove(Fan f){
fans.remove(f); Celebrity class may look like this.
}
void notify(){
Now add the Fan class
foreach( Fan f: fans)
f.update(this);
}
void setState(int newState){
state = newState;
notify();
}
int getState(){
return state;
}

}
Observer Pattern 15

public class Celebrity{


private List<Fan> fans = new ArrayList<Fan>();
private int state; public class Fan{
void attach(Fan f){ private List<Celebrity> celebrities= new
fans.add(f); ArrayList<Celebrity>();
} void update(Celebrity c){
void remove(Fan f){
c.getState();
fans.remove(f);
} }
void notify(){ void addCelebrity(Celebrity c){
foreach( Fan f: fans) celebrities.add(c);
f.update(this); c.attach(this);
} }
void setState(int newState){
void removeCelebrity(Celebrity c){
state = newState;
notify(); celebrities.remove(c);
} c.remove(this);
int getState(){ }
return state;
}
}
}
Observer Pattern 16

From main method –


Fan f1 = new Fan();
Fan f2 = new Fan();

Celebrity c1 = new Celebrity ();


Celebrity c2 = new Celebrity ();

f1.addCelebrity(c1);
f1.addCelebrity(c2);
f2.addCelebrity (c1);

c1.setState(5); //new State


c2.setState(2); //newState
Participants 17

● Subject: knows its observers. Any number of Observer objects may


observe a subject. It sends a notification to its observers when its state
changes. (ex: Celebrity)
● Observer: defines an updating interface for objects that should be notified
changes in a subject. (ex: Fans)
● ConcreteSubject: (ex: FilmCelebrity, FashionCelebrity)
● ConcreteObserver (ex: FilmFan, FashsionFan)
Structure 18
Advanced Observer with Concrete 19

subjects and observers


Public FilmCelebrity extends
Celebrity{
private int state;
void setState(int newState){
state = newState;
notify();
}
int getState(){
return state;
}
}
Advanced Observer with Concrete 20

subjects and observers


Public FilmCelebrity extends public class FilmFan extends Fan{
private List<FilmCelebrity> filmCelebrities= new
Celebrity{ ArrayList<FilmCelebrity>();
private int state; void update(FilmCelebrity fc){
if(filmCelebrities.contain(fc){
void setState(int newState){ fc.getState();
state = newState; }
}
notify(); void addCelebrity(FilmCelebrity fc){
} celebrities.add(fc);
fc.attach(this);
int getState(){ }
return state; void removeCelebrity(FilmCelebrity fc){
celebrities.remove(fc);
} fc.remove(this);
} }

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