SlideShare a Scribd company logo
1 of 24
2
3
 Name: Singleton
 Intent: Ensure a class has only one instance and
provide a global point of access to it
 Problem: How can we guarantee that one and only one
instance of a class can be created?
 Solution: Define a class with a private constructor.
The class constructs a single instance of itself
Supply a static method that returns a reference to
the single instance.
4
5
6
 A status bar ….It could be implemented as a Singleton
object, allowing only one instance and a focal point for
updates.
 One file system, one window manager, one printer
spooler, one Test engine, one Input/Output socket ,
Windows Registry etc.
7
Class Singleton {
private static Singleton uniqueInstance = null;
private Singleton( ) { .. } // private constructor
public static Singleton getInstance( ) {
if (uniqueInstance == null)
uniqueInstance = new Singleton();
// call constructor
return uniqueInstance;
}
}
Singleton: Basic Implementation
8
 We want to create a remote connection to a
server / database system and assure that only one
connection is present.
 Apply Singleton pattern
9
Class RemoteConnection{
private static RemoteConnetion remoteConn;
private RemoteConnection(){…} //private Constructor
public static RemoteConnection getInstance(){
if(remoteConn == null){
remoteConn = new RemoteConnection();
}
return remoteConn;
}
}
In a university….when a student changes his
address…pass this information to:
Exams department
transport department
What's the solution?
10
11
Different Objects
Different Interfaces
Observers
Observable
12
 Name: Observer
 Intent: Define a one-to-many dependency between
objects so that when one object changes state, all its
dependents are notified and updated automatically.
 Problem: You need to notify a varying list of objects
that an event has occurred.
 Solution: delegate the responsibility for monitoring an
event to a central object.
13
 Step 1: Make the Observers behave in the same way
 Step 2: Have the observers register themselves
 Step 3: Notify the observers when the event occurs
 Step 4: Get the information from the observable
14
15
16
public interface myObserver{
public void update(Student s);
}
17
class ExamDept implements myObserver{
public void update(Student s){
System.out.println("Student Updated in Exam Dept");
System.out.println("New Address: "+ s.getAddress());
}
}
18
class TransportDept implements myObserver{
public void update(Student s){
System.out.println("Student Updated in TD");
System.out.println("New Address:
"+s.getAddress());
}
}
19
class Student{
private String address;
private Vector myObs;
public Student(){ myObs = new Vector(); address = "Rawalpindi"; }
public void register(myObserver obs){ myObs.addElement(obs); }
public void unRegister(myObserver obs){ myObs.remove(obs); }
public void notifyObs(){
Enumeration e = myObs.elements();
while(e.hasMoreElements()){
((myObserver)e.nextElement()).update(this); } }
public void changeAddress(){ address = "Islamabad"; notifyObs(); }
}
20
class Main{
public static void main(String[]args){
Student s = new Student();
TransportDept td = new TransportDept();
ExamDept ed = new ExamDept();
System.out.println("Present Address:" + s.getAddress());
s.register(td);
s.register(ed);
s.changeAddress();
System.out.println("******Unregister Exam Dept*******");
s.unRegister(ed);
s.changeAddress();
}
}
21
22
Suppose you are working on an MDI (Multiple
Documents Interface) Form that has several child.
You need to notify all the child about the changes
that occur in MDI form (e.g title changed).
Apply Observer pattern to solve this problem and
draw the corresponding class diagram.
23
24

More Related Content

What's hot

Directory and discovery services
Directory and discovery servicesDirectory and discovery services
Directory and discovery servicesRamchandraRegmi
 
Module 2 Foot Printing
Module 2   Foot PrintingModule 2   Foot Printing
Module 2 Foot Printingleminhvuong
 
Digital Forensic: Brief Intro & Research Challenge
Digital Forensic: Brief Intro & Research ChallengeDigital Forensic: Brief Intro & Research Challenge
Digital Forensic: Brief Intro & Research ChallengeAung Thu Rha Hein
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
Tools for Cyber Security | Cyber Security
Tools for Cyber Security | Cyber SecurityTools for Cyber Security | Cyber Security
Tools for Cyber Security | Cyber SecurityCyber Security Experts
 
How to Hunt for Lateral Movement on Your Network
How to Hunt for Lateral Movement on Your NetworkHow to Hunt for Lateral Movement on Your Network
How to Hunt for Lateral Movement on Your NetworkSqrrl
 
Hunting for Credentials Dumping in Windows Environment
Hunting for Credentials Dumping in Windows EnvironmentHunting for Credentials Dumping in Windows Environment
Hunting for Credentials Dumping in Windows EnvironmentTeymur Kheirkhabarov
 
Reconnaissance & Scanning
Reconnaissance & ScanningReconnaissance & Scanning
Reconnaissance & Scanningamiable_indian
 
Best Practices for Configuring Your OSSIM Installation
Best Practices for Configuring Your OSSIM InstallationBest Practices for Configuring Your OSSIM Installation
Best Practices for Configuring Your OSSIM InstallationAlienVault
 
Java package
Java packageJava package
Java packageCS_GDRCST
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVAJalpesh Vasa
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Ganglia Monitoring Tool
Ganglia Monitoring ToolGanglia Monitoring Tool
Ganglia Monitoring Toolsudhirpg
 

What's hot (20)

Directory and discovery services
Directory and discovery servicesDirectory and discovery services
Directory and discovery services
 
Module 2 Foot Printing
Module 2   Foot PrintingModule 2   Foot Printing
Module 2 Foot Printing
 
Digital Forensic: Brief Intro & Research Challenge
Digital Forensic: Brief Intro & Research ChallengeDigital Forensic: Brief Intro & Research Challenge
Digital Forensic: Brief Intro & Research Challenge
 
Data Acquisition
Data AcquisitionData Acquisition
Data Acquisition
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Tools for Cyber Security | Cyber Security
Tools for Cyber Security | Cyber SecurityTools for Cyber Security | Cyber Security
Tools for Cyber Security | Cyber Security
 
How to Hunt for Lateral Movement on Your Network
How to Hunt for Lateral Movement on Your NetworkHow to Hunt for Lateral Movement on Your Network
How to Hunt for Lateral Movement on Your Network
 
Hunting for Credentials Dumping in Windows Environment
Hunting for Credentials Dumping in Windows EnvironmentHunting for Credentials Dumping in Windows Environment
Hunting for Credentials Dumping in Windows Environment
 
Reconnaissance & Scanning
Reconnaissance & ScanningReconnaissance & Scanning
Reconnaissance & Scanning
 
Best Practices for Configuring Your OSSIM Installation
Best Practices for Configuring Your OSSIM InstallationBest Practices for Configuring Your OSSIM Installation
Best Practices for Configuring Your OSSIM Installation
 
Wireshark Tutorial
Wireshark TutorialWireshark Tutorial
Wireshark Tutorial
 
Security monitoring and auditing
Security monitoring and auditingSecurity monitoring and auditing
Security monitoring and auditing
 
Java String
Java String Java String
Java String
 
Java package
Java packageJava package
Java package
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVA
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Windowsforensics
WindowsforensicsWindowsforensics
Windowsforensics
 
Log Files
Log FilesLog Files
Log Files
 
Incident handling.final
Incident handling.finalIncident handling.final
Incident handling.final
 
Ganglia Monitoring Tool
Ganglia Monitoring ToolGanglia Monitoring Tool
Ganglia Monitoring Tool
 

Viewers also liked

Design Pattern - 2. Observer
Design Pattern -  2. ObserverDesign Pattern -  2. Observer
Design Pattern - 2. ObserverFrancesco Ierna
 
Observer pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expressionObserver pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expressionLearningTech
 
Design patterns
Design patternsDesign patterns
Design patternsISsoft
 
The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)John Ortiz
 
Design patterns: observer pattern
Design patterns: observer patternDesign patterns: observer pattern
Design patterns: observer patternJyaasa Technologies
 
Observer Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 AugObserver Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 Augmelbournepatterns
 
Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - observer patternpixelblend
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa TouchEliah Nikans
 
Reflective portfolio
Reflective portfolioReflective portfolio
Reflective portfoliojobbo1
 
Design Pattern - Observer Pattern
Design Pattern - Observer PatternDesign Pattern - Observer Pattern
Design Pattern - Observer PatternMudasir Qazi
 
Observer design pattern
Observer design patternObserver design pattern
Observer design patternSara Torkey
 
Observer Pattern
Observer PatternObserver Pattern
Observer PatternAkshat Vig
 
Observer design pattern
Observer design patternObserver design pattern
Observer design patternSameer Rathoud
 

Viewers also liked (20)

Singleton pattern
Singleton patternSingleton pattern
Singleton pattern
 
Design Pattern - 2. Observer
Design Pattern -  2. ObserverDesign Pattern -  2. Observer
Design Pattern - 2. Observer
 
Observer pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expressionObserver pattern, delegate, event, lambda expression
Observer pattern, delegate, event, lambda expression
 
Design patterns
Design patternsDesign patterns
Design patterns
 
The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Design patterns: observer pattern
Design patterns: observer patternDesign patterns: observer pattern
Design patterns: observer pattern
 
Observer Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 AugObserver Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 Aug
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - observer pattern
 
Factory Pattern
Factory PatternFactory Pattern
Factory Pattern
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
 
Reflective portfolio
Reflective portfolioReflective portfolio
Reflective portfolio
 
Design patterns - Observer Pattern
Design patterns - Observer PatternDesign patterns - Observer Pattern
Design patterns - Observer Pattern
 
Design Pattern - Observer Pattern
Design Pattern - Observer PatternDesign Pattern - Observer Pattern
Design Pattern - Observer Pattern
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Observer Pattern
Observer PatternObserver Pattern
Observer Pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 

Similar to Observer & singleton pattern

Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern11prasoon
 
Factory method, strategy pattern & chain of responsibilities
Factory method, strategy pattern & chain of responsibilitiesFactory method, strategy pattern & chain of responsibilities
Factory method, strategy pattern & chain of responsibilitiesbabak danyal
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeMacoscope
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Arsen Gasparyan
 
Core Java- An advanced review of features
Core Java- An advanced review of featuresCore Java- An advanced review of features
Core Java- An advanced review of featuresvidyamittal
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
Factory method & strategy pattern
Factory method & strategy patternFactory method & strategy pattern
Factory method & strategy patternbabak danyal
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot trainingMallikarjuna G D
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805LearningTech
 
Building a Driver: Lessons Learned From Developing the Internet Explorer Driver
Building a Driver: Lessons Learned From Developing the Internet Explorer DriverBuilding a Driver: Lessons Learned From Developing the Internet Explorer Driver
Building a Driver: Lessons Learned From Developing the Internet Explorer Driverseleniumconf
 
Android Unit Test
Android Unit TestAndroid Unit Test
Android Unit TestPhuoc Bui
 

Similar to Observer & singleton pattern (20)

Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
04 threads
04 threads04 threads
04 threads
 
Factory method, strategy pattern & chain of responsibilities
Factory method, strategy pattern & chain of responsibilitiesFactory method, strategy pattern & chain of responsibilities
Factory method, strategy pattern & chain of responsibilities
 
C# Unit 2 notes
C# Unit 2 notesC# Unit 2 notes
C# Unit 2 notes
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
Core Java- An advanced review of features
Core Java- An advanced review of featuresCore Java- An advanced review of features
Core Java- An advanced review of features
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Factory method & strategy pattern
Factory method & strategy patternFactory method & strategy pattern
Factory method & strategy pattern
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805Design pattern proxy介紹 20130805
Design pattern proxy介紹 20130805
 
Building a Driver: Lessons Learned From Developing the Internet Explorer Driver
Building a Driver: Lessons Learned From Developing the Internet Explorer DriverBuilding a Driver: Lessons Learned From Developing the Internet Explorer Driver
Building a Driver: Lessons Learned From Developing the Internet Explorer Driver
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
 
Android Unit Test
Android Unit TestAndroid Unit Test
Android Unit Test
 

More from babak danyal

Easy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client SocketsEasy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client Socketsbabak danyal
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streamsbabak danyal
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Javababak danyal
 
block ciphers and the des
block ciphers and the desblock ciphers and the des
block ciphers and the desbabak danyal
 
key distribution in network security
key distribution in network securitykey distribution in network security
key distribution in network securitybabak danyal
 
Lecture10 Signal and Systems
Lecture10 Signal and SystemsLecture10 Signal and Systems
Lecture10 Signal and Systemsbabak danyal
 
Lecture8 Signal and Systems
Lecture8 Signal and SystemsLecture8 Signal and Systems
Lecture8 Signal and Systemsbabak danyal
 
Lecture7 Signal and Systems
Lecture7 Signal and SystemsLecture7 Signal and Systems
Lecture7 Signal and Systemsbabak danyal
 
Lecture6 Signal and Systems
Lecture6 Signal and SystemsLecture6 Signal and Systems
Lecture6 Signal and Systemsbabak danyal
 
Lecture5 Signal and Systems
Lecture5 Signal and SystemsLecture5 Signal and Systems
Lecture5 Signal and Systemsbabak danyal
 
Lecture4 Signal and Systems
Lecture4  Signal and SystemsLecture4  Signal and Systems
Lecture4 Signal and Systemsbabak danyal
 
Lecture3 Signal and Systems
Lecture3 Signal and SystemsLecture3 Signal and Systems
Lecture3 Signal and Systemsbabak danyal
 
Lecture2 Signal and Systems
Lecture2 Signal and SystemsLecture2 Signal and Systems
Lecture2 Signal and Systemsbabak danyal
 
Lecture1 Intro To Signa
Lecture1 Intro To SignaLecture1 Intro To Signa
Lecture1 Intro To Signababak danyal
 
Lecture9 Signal and Systems
Lecture9 Signal and SystemsLecture9 Signal and Systems
Lecture9 Signal and Systemsbabak danyal
 
Cns 13f-lec03- Classical Encryption Techniques
Cns 13f-lec03- Classical Encryption TechniquesCns 13f-lec03- Classical Encryption Techniques
Cns 13f-lec03- Classical Encryption Techniquesbabak danyal
 
Classical Encryption Techniques in Network Security
Classical Encryption Techniques in Network SecurityClassical Encryption Techniques in Network Security
Classical Encryption Techniques in Network Securitybabak danyal
 

More from babak danyal (20)

applist
applistapplist
applist
 
Easy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client SocketsEasy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client Sockets
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Java
 
Tcp sockets
Tcp socketsTcp sockets
Tcp sockets
 
block ciphers and the des
block ciphers and the desblock ciphers and the des
block ciphers and the des
 
key distribution in network security
key distribution in network securitykey distribution in network security
key distribution in network security
 
Lecture10 Signal and Systems
Lecture10 Signal and SystemsLecture10 Signal and Systems
Lecture10 Signal and Systems
 
Lecture8 Signal and Systems
Lecture8 Signal and SystemsLecture8 Signal and Systems
Lecture8 Signal and Systems
 
Lecture7 Signal and Systems
Lecture7 Signal and SystemsLecture7 Signal and Systems
Lecture7 Signal and Systems
 
Lecture6 Signal and Systems
Lecture6 Signal and SystemsLecture6 Signal and Systems
Lecture6 Signal and Systems
 
Lecture5 Signal and Systems
Lecture5 Signal and SystemsLecture5 Signal and Systems
Lecture5 Signal and Systems
 
Lecture4 Signal and Systems
Lecture4  Signal and SystemsLecture4  Signal and Systems
Lecture4 Signal and Systems
 
Lecture3 Signal and Systems
Lecture3 Signal and SystemsLecture3 Signal and Systems
Lecture3 Signal and Systems
 
Lecture2 Signal and Systems
Lecture2 Signal and SystemsLecture2 Signal and Systems
Lecture2 Signal and Systems
 
Lecture1 Intro To Signa
Lecture1 Intro To SignaLecture1 Intro To Signa
Lecture1 Intro To Signa
 
Lecture9 Signal and Systems
Lecture9 Signal and SystemsLecture9 Signal and Systems
Lecture9 Signal and Systems
 
Lecture9
Lecture9Lecture9
Lecture9
 
Cns 13f-lec03- Classical Encryption Techniques
Cns 13f-lec03- Classical Encryption TechniquesCns 13f-lec03- Classical Encryption Techniques
Cns 13f-lec03- Classical Encryption Techniques
 
Classical Encryption Techniques in Network Security
Classical Encryption Techniques in Network SecurityClassical Encryption Techniques in Network Security
Classical Encryption Techniques in Network Security
 

Recently uploaded

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 

Recently uploaded (20)

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 

Observer & singleton pattern

  • 1.
  • 2. 2
  • 3. 3  Name: Singleton  Intent: Ensure a class has only one instance and provide a global point of access to it  Problem: How can we guarantee that one and only one instance of a class can be created?  Solution: Define a class with a private constructor. The class constructs a single instance of itself Supply a static method that returns a reference to the single instance.
  • 4. 4
  • 5. 5
  • 6. 6  A status bar ….It could be implemented as a Singleton object, allowing only one instance and a focal point for updates.  One file system, one window manager, one printer spooler, one Test engine, one Input/Output socket , Windows Registry etc.
  • 7. 7 Class Singleton { private static Singleton uniqueInstance = null; private Singleton( ) { .. } // private constructor public static Singleton getInstance( ) { if (uniqueInstance == null) uniqueInstance = new Singleton(); // call constructor return uniqueInstance; } } Singleton: Basic Implementation
  • 8. 8  We want to create a remote connection to a server / database system and assure that only one connection is present.  Apply Singleton pattern
  • 9. 9 Class RemoteConnection{ private static RemoteConnetion remoteConn; private RemoteConnection(){…} //private Constructor public static RemoteConnection getInstance(){ if(remoteConn == null){ remoteConn = new RemoteConnection(); } return remoteConn; } }
  • 10. In a university….when a student changes his address…pass this information to: Exams department transport department What's the solution? 10
  • 12. 12
  • 13.  Name: Observer  Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.  Problem: You need to notify a varying list of objects that an event has occurred.  Solution: delegate the responsibility for monitoring an event to a central object. 13
  • 14.  Step 1: Make the Observers behave in the same way  Step 2: Have the observers register themselves  Step 3: Notify the observers when the event occurs  Step 4: Get the information from the observable 14
  • 15. 15
  • 16. 16
  • 17. public interface myObserver{ public void update(Student s); } 17
  • 18. class ExamDept implements myObserver{ public void update(Student s){ System.out.println("Student Updated in Exam Dept"); System.out.println("New Address: "+ s.getAddress()); } } 18
  • 19. class TransportDept implements myObserver{ public void update(Student s){ System.out.println("Student Updated in TD"); System.out.println("New Address: "+s.getAddress()); } } 19
  • 20. class Student{ private String address; private Vector myObs; public Student(){ myObs = new Vector(); address = "Rawalpindi"; } public void register(myObserver obs){ myObs.addElement(obs); } public void unRegister(myObserver obs){ myObs.remove(obs); } public void notifyObs(){ Enumeration e = myObs.elements(); while(e.hasMoreElements()){ ((myObserver)e.nextElement()).update(this); } } public void changeAddress(){ address = "Islamabad"; notifyObs(); } } 20
  • 21. class Main{ public static void main(String[]args){ Student s = new Student(); TransportDept td = new TransportDept(); ExamDept ed = new ExamDept(); System.out.println("Present Address:" + s.getAddress()); s.register(td); s.register(ed); s.changeAddress(); System.out.println("******Unregister Exam Dept*******"); s.unRegister(ed); s.changeAddress(); } } 21
  • 22. 22
  • 23. Suppose you are working on an MDI (Multiple Documents Interface) Form that has several child. You need to notify all the child about the changes that occur in MDI form (e.g title changed). Apply Observer pattern to solve this problem and draw the corresponding class diagram. 23
  • 24. 24