SlideShare a Scribd company logo
1 of 47
Professional Practices
Course Instructor : DR. Masroor Ahmed Bhatti
Design Pattern
Introduction
Singleton, Observer & Factory Design
Pattern.
Group Members
I. Syed Danish Abbas BSCS 11-37
II. Ahsan Rasheed BSCS 11-39
III. Bilal Ejaz BSCS 11-52
Agenda
 Introduction to Design Pattern
i. What is a Design Pattern?
ii. Why study Design Pattern?
iii. The Gang of Four (GOF).
 Singleton Design Pattern
 Observer Design Pattern
 Factory Design Pattern
What is a Design Pattern ?
1. A problem that someone has already solved.
2. A model or design to use as a guide.
3. More formally: “A proven solution to a common problem in a specified
context."
Real World Examples:
i. Blueprint for a house
ii. Manufacturing
Why Study Design Patterns?
1. Provides software developers a toolkit for handling problems that have already
been solved.
2. Provides a vocabulary that can be used amongst software developers (The
Pattern Name itself helps establish a vocabulary).
3. Helps you think about how to solve a software problem.
The Gang of Four
Defines a Catalog of different design patterns.
 Three different types :
I. Creational – “Creating objects in a manner suitable for the situation”
II. Structural – “Ease the design by identifying a simple way to realize relationships
between entities”
III. Behavioral – “Common communication patterns between objects”
The Gang of Four:
1. Creational 3. Behavioral
Abstract Factory Chain of Responsibility
Builder Command
Factory Method Interpreter
Prototype Iterator
Singleton Mediator
2. Structural Memento
Adapter Observer
Bridge State
Composite Strategy
Decorator Template Method
Façade Visitor
Flyweight
Proxy
Patterns in Red we will discuss in this
presentation !!
Singleton Pattern
(Creational)
Singleton Pattern
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.
Singleton: Basic Structure
Singleton
- instance: Singleton
- Singleton();
+ getInstance(): Singleton
Singleton sequence diagram
Singleton Participants
1. Singleton
a) Defines an Instance operation that lets clients access its unique
instance. Instance is a class operation (static method).
b) May be responsible for creating its own unique instance
2. Client
a) Accesses a Singleton instance solely through the Singleton’s
Instance() method.
Singleton – Example
1) A status bar ….It could be implemented as a Singleton object, allowing only
one instance and a focal point for updates.
2) One file system, one window manager, one printer spooler, one Test engine,
one Input/output socket, Windows Registry etc.
Singleton: Basic Implementation
Class Singleton {
private static Singleton unique Instance = null;
private Singleton( ) { .. } // private constructor
public static Singleton getInstance( ) {
if (uniqueInstance == null)
uniqueInstance = new Singleton(); // call constructor
return uniqueInstance;
}
}
Case Study
 We want to create a remote connection to a server / database
system and assure that only one connection is present.
. Apply Singleton pattern
Implementation : RemoteConnection
Class RemoteConnection{
private static RemoteConnetion remoteConn;
private RemoteConnection(){…} //private
Constructor
public static RemoteConnection getInstance(){
if( remoteConn == null ){
remoteConn = new RemoteConnection();
}
return remoteConn;
}
}
Lazy Instantiation
1) Objects are only created when it is needed.
2) Helps control that we’ve created the Singleton just once.
3) If it is resource intensive to set up, we want to do it once.
Singleton Consequences:
I. Controlled access to sole instance facilitates strict control
over when and how the clients access it.
II. The singleton patter is improvement over global variables.
III. It is easy to configure an instance of the application that extends
the functionality of singleton at run-time.
IV. More flexible than class operations.
Singleton Limitations:
1) The main limitation of the singleton pattern is that is permits the
creation of only one instance of the class, while most practical
applications require multiple instances to be initialized.
2) Furthermore, in case of singleton, the system threads fight to
access the single instance thereby degrading the performance of
the applications.
Observer Pattern
(Behavioral)
Observer Pattern (Behavioral)
Intent : Define a one-to-many dependency between objects so
that when one object changes state, all its dependents are notified
and updated automatically.
Also Known As : Dependents, Publish-Subscribe, Delegation Event
Model.
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.
Basic Structure
Participants in structure
 Subject (interface):
• Store the list of attached observers and provide operations for adding and removing the
observer objects.
• Expose an operation to notify all the attached observers
 Observer (interface):
• Defines an interface for updating mechanism.
 ConcreteSubject:
Get the update either from an external source or from any of the attached observer
and notify the attached observers in case of change state.
 ConcreteObserver:
• Maintains a reference to a ConcreteSubject object.
• Stores state that should stay consistent with the subject's.
• Implements the Observer updating interface to keep its state consistent with the
subject's
Applying the Observer
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.
A case study…
In a university….when a student changes his address…pass this
information to:
a) Exams department
b) Transport department.
What's the solution?
Applying observer to case study
Implementation: Observer interface
public interface myObserver
{
public void update(Student s);
}
Implementation: ExamDept
class ExamDept implements myObserver
{
public void update(Student s){
System.out.println("Student Updated in Exam Dept");
System.out.println("New Address: "+ s.getAddress());
}
}
Implementation: TransportDept
class TransportDept implements myObserver
{
public void update(Student s)
{
System.out.println("Student Updated in TD");
System.out.println("New Address: "+s.getAddress());
}
}
Implementation: Student
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(); }
}
Implementation: Main
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 (); }}
Real Life Example
Auctions:
“Auctions demonstrate this pattern. Each bidder possesses a numbered paddle
that is used to indicate a bid. The auctioneer starts the bidding, and "observes" when a
paddle is raised to accept the bid. The acceptance of the bid changes the bid price which
is broadcast to all of the bidders in the form of a new bid”
Pros & Cons
Pros :
i. Decoupling of subject and observer, each can be extended and reused
individually.
ii. Dynamic addition and removal of observers at runtime.
iii. Subject broadcasts notification automatically to all interested objects, no
matter how many or which kind of observers are registered.
Cons :
i. May result in many notifications the observers are not interested in
ii. Potentially difficult for the observers to figure out the specific state change of
the subject.
Factory Pattern
(Creational)
Factory- Creational Pattern
Intent:
“Define an interface for creating an object, but let
subclasses decide which class to instantiate”
Also Known as Virtual Constructor.
Problem:
“A framework needs to standardize the architectural model for a
range of applications, but allow for individual applications to define
their own domain objects and provide for their instantiation”
Solution:
 Factory Method Pattern offer a solution. It encapsulates the
knowledge of which Document subclass to create and moves this
knowledge out of the framework.
 Application subclasses redefine an abstract CreateDocument( ) on
Application to return an appropriate Document subclass.
 Once an application subclass is instantiated , It can then
instantiate application – specific Documents without knowing
their Class , We call CreateDocument( ) a Factory Method
because it is responsible for manufacturing an object.
Structure
Participants:
 Product( IHttpHandler)
. Defines the interface of objects the factory method creates.
 ConcreteProduct ( ASP.SamplePage_aspx )
. Implements the Product Interface.
 Creator ( IHttpHandlerFactory )
. Declares the factory method and may provide a default
implementation for it.
. It returns an object of type Product.
 ConcreteCreator( PageHandlerFactory )
. Overrides the factory method to return an instance of
ConcreteProduct.
Implementation:
 Two major varieties:
1. Abstract Creator class with no default implementation
2. Concrete Creator with default implementation.
 Solutions:
1. Parameterized Methods
2. Templates
Parameterized Factory Method:
class Creator {
public:
virtual Product* Create( ProductID id ) {
if (id == P1) return new MyProduct ;
if (id == P2) return new YourProduct;
// other products ...
return 0;
}};
// You can subclass the Creator to handle more IDs
Product* MyCreator::Create(ProductID id) {
if (id == P3) return new TheirProduct; // Handle other IDs
return this->Creator::Create(id); };
Templatized Factory Methods:
class Creator { public:
Creator() {
// You cannot call the factory method here (why?)
// Use lazy initialization instead }
virtual Product* CreateProduct() = 0;
};
template <class T>
class StandardCreator: public Creator {
public:
virtual Product* CreateProduct() {
return new T; }}
// In the Client
StandardCreator<MyProduct> myCreator
Consequences:
I. The code deals with only with the product interface, therefore it
can work with any user defined Concrete Product classes
(decoupling subclass details from client classes).
II. New concrete classes can be added without recompiling the
existing code.
III. It may lead to many subclasses if the product objects requires one
or more additional objects. (Parallel class hierarchy)
Known Uses:
I. It is a very pervasive pattern.
II. It is used in several places in the Java API. For example,
URLConnection has a method getContent that returns the content
as an appropriate object (html, gif etc.)
III. FCL ( .Net Framework Class Library) is no exception to the use
of Factory Method Pattern. For example, it is used in
Systems.Collections.IEnumerable, System.Net.WebRequest,
System.Security.Cryptography
Real Life Example:
Hotel:
“One good example for the Factory Method is the Hotel. When Check in,
the person gets the key from the front desk where he can be looked up
as the ‘room’ factory. Now if he wants to make a phone call to some
outside office, he will contact the front desk to make the connection to
that call which means the front desk is acting as an interface.”
But…..
This presentation could not be completed without…
The sources of information:
1. http://www.dofactory.com/Patterns/PatternObserver.aspx
2. http://www.vincehuston.org/dp/observer.html
3. http://en.wikipedia.org/wiki/Design_pattern
4. http://sourcemaking.com/design_patterns
5. Design Patterns: Elements of Reusable Object-oriented Software, by Erich Gamma,
Richard Helm, Ralph Johnson, John Vlissides, 1995 – “Gang of Four”.
6. Design Patterns in Ruby – Russ Olsen
7. Head First Design Patterns – Elisabeth Freeman, Eric Freeman, Bert Bates and Kathy
Sierra
8. Special Thanks to Dr. Masroor Bhatti for providing us the chance to speak on Design
Patterns.
If(Questions)
{
Ask;
}
else
{
Thank you;
}

More Related Content

What's hot

Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patternsAmit Kabra
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonJonathan Simon
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)paramisoft
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design patternMindfire Solutions
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsMichael Heron
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern11prasoon
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns pptmkruthika
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General IntroductionAsma CHERIF
 
Design Pattern - Singleton Pattern
Design Pattern - Singleton PatternDesign Pattern - Singleton Pattern
Design Pattern - Singleton PatternMudasir Qazi
 
Creational pattern
Creational patternCreational pattern
Creational patternHimanshu
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Patternsahilrk911
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan GoleChetan Gole
 

What's hot (20)

Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patterns
 
Design Patterns.ppt
Design Patterns.pptDesign Patterns.ppt
Design Patterns.ppt
 
Introduction to Design Patterns and Singleton
Introduction to Design Patterns and SingletonIntroduction to Design Patterns and Singleton
Introduction to Design Patterns and Singleton
 
Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)Design pattern (Abstract Factory & Singleton)
Design pattern (Abstract Factory & Singleton)
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 
PATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design PatternsPATTERNS04 - Structural Design Patterns
PATTERNS04 - Structural Design Patterns
 
Singleton design pattern
Singleton design patternSingleton design pattern
Singleton design pattern
 
Facade pattern
Facade patternFacade pattern
Facade pattern
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 
Software Architecture
Software ArchitectureSoftware Architecture
Software Architecture
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 
Design pattern
Design patternDesign pattern
Design pattern
 
Design Pattern - Singleton Pattern
Design Pattern - Singleton PatternDesign Pattern - Singleton Pattern
Design Pattern - Singleton Pattern
 
Creational pattern
Creational patternCreational pattern
Creational pattern
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Factory Method Pattern
Factory Method PatternFactory Method Pattern
Factory Method Pattern
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 

Viewers also liked

Konstantin slisenko - Design patterns
Konstantin slisenko - Design patternsKonstantin slisenko - Design patterns
Konstantin slisenko - Design patternsbeloslab
 
Observer Software Design Pattern
Observer Software Design Pattern Observer Software Design Pattern
Observer Software Design Pattern Nirthika Rajendran
 
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
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software EngineeringNadimozzaman Pappo
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator PatternJonathan Simon
 
55 New Features in JDK 9
55 New Features in JDK 955 New Features in JDK 9
55 New Features in JDK 9Simon Ritter
 

Viewers also liked (13)

Konstantin slisenko - Design patterns
Konstantin slisenko - Design patternsKonstantin slisenko - Design patterns
Konstantin slisenko - Design patterns
 
L05 Design Patterns
L05 Design PatternsL05 Design Patterns
L05 Design Patterns
 
Observer Software Design Pattern
Observer Software Design Pattern Observer Software Design Pattern
Observer Software Design Pattern
 
Observer Pattern
Observer PatternObserver Pattern
Observer Pattern
 
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 design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Observer Pattern
Observer PatternObserver Pattern
Observer Pattern
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software Engineering
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator Pattern
 
55 New Features in JDK 9
55 New Features in JDK 955 New Features in JDK 9
55 New Features in JDK 9
 

Similar to Design pattern-presentation

Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton patternbabak danyal
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patternsamitarcade
 
1. Mini seminar intro
1. Mini seminar intro1. Mini seminar intro
1. Mini seminar introLeonid Maslov
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
lecture10-patterns.ppt
lecture10-patterns.pptlecture10-patterns.ppt
lecture10-patterns.pptAnkitPangasa1
 
lecture10-patterns.ppt
lecture10-patterns.pptlecture10-patterns.ppt
lecture10-patterns.pptbryafaissal
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design PatternsSteven Smith
 
Sofwear deasign and need of design pattern
Sofwear deasign and need of design patternSofwear deasign and need of design pattern
Sofwear deasign and need of design patternchetankane
 
C#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course ContentC#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course ContentSVRTechnologies
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Steven Smith
 
Assignment 4- Implementing a Banking Application Due See course shel.pdf
 Assignment 4- Implementing a Banking Application Due See course shel.pdf Assignment 4- Implementing a Banking Application Due See course shel.pdf
Assignment 4- Implementing a Banking Application Due See course shel.pdfamarhandi
 
Software Engineering with Objects (M363) Final Revision By Kuwait10
Software Engineering with Objects (M363) Final Revision By Kuwait10Software Engineering with Objects (M363) Final Revision By Kuwait10
Software Engineering with Objects (M363) Final Revision By Kuwait10Kuwait10
 

Similar to Design pattern-presentation (20)

Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton pattern
 
Sda 8
Sda   8Sda   8
Sda 8
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
1. Mini seminar intro
1. Mini seminar intro1. Mini seminar intro
1. Mini seminar intro
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
lecture10-patterns.ppt
lecture10-patterns.pptlecture10-patterns.ppt
lecture10-patterns.ppt
 
lecture10-patterns.ppt
lecture10-patterns.pptlecture10-patterns.ppt
lecture10-patterns.ppt
 
Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Sofwear deasign and need of design pattern
Sofwear deasign and need of design patternSofwear deasign and need of design pattern
Sofwear deasign and need of design pattern
 
C#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course ContentC#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course Content
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
Assignment 4- Implementing a Banking Application Due See course shel.pdf
 Assignment 4- Implementing a Banking Application Due See course shel.pdf Assignment 4- Implementing a Banking Application Due See course shel.pdf
Assignment 4- Implementing a Banking Application Due See course shel.pdf
 
Software Engineering with Objects (M363) Final Revision By Kuwait10
Software Engineering with Objects (M363) Final Revision By Kuwait10Software Engineering with Objects (M363) Final Revision By Kuwait10
Software Engineering with Objects (M363) Final Revision By Kuwait10
 

More from Rana Muhammad Asif

Software engineering-codes-of-ethics (1)
Software engineering-codes-of-ethics (1)Software engineering-codes-of-ethics (1)
Software engineering-codes-of-ethics (1)Rana Muhammad Asif
 
Intellectual properties and laws
Intellectual properties and lawsIntellectual properties and laws
Intellectual properties and lawsRana Muhammad Asif
 
Ieee institute-of-electrical-and-electronics-engineers (1)
Ieee institute-of-electrical-and-electronics-engineers (1)Ieee institute-of-electrical-and-electronics-engineers (1)
Ieee institute-of-electrical-and-electronics-engineers (1)Rana Muhammad Asif
 
Association for computing machinery (acm)
Association for computing machinery (acm)Association for computing machinery (acm)
Association for computing machinery (acm)Rana Muhammad Asif
 

More from Rana Muhammad Asif (8)

Software engineering-codes-of-ethics (1)
Software engineering-codes-of-ethics (1)Software engineering-codes-of-ethics (1)
Software engineering-codes-of-ethics (1)
 
Software licencing techniqes
Software licencing techniqesSoftware licencing techniqes
Software licencing techniqes
 
Intellectual properties and laws
Intellectual properties and lawsIntellectual properties and laws
Intellectual properties and laws
 
Ieee institute-of-electrical-and-electronics-engineers (1)
Ieee institute-of-electrical-and-electronics-engineers (1)Ieee institute-of-electrical-and-electronics-engineers (1)
Ieee institute-of-electrical-and-electronics-engineers (1)
 
Health and safety at work
Health and safety at workHealth and safety at work
Health and safety at work
 
Cyber laws in pakistan
Cyber laws in pakistanCyber laws in pakistan
Cyber laws in pakistan
 
Black box software testing
Black box software testingBlack box software testing
Black box software testing
 
Association for computing machinery (acm)
Association for computing machinery (acm)Association for computing machinery (acm)
Association for computing machinery (acm)
 

Design pattern-presentation

  • 1. Professional Practices Course Instructor : DR. Masroor Ahmed Bhatti Design Pattern Introduction Singleton, Observer & Factory Design Pattern.
  • 2. Group Members I. Syed Danish Abbas BSCS 11-37 II. Ahsan Rasheed BSCS 11-39 III. Bilal Ejaz BSCS 11-52
  • 3. Agenda  Introduction to Design Pattern i. What is a Design Pattern? ii. Why study Design Pattern? iii. The Gang of Four (GOF).  Singleton Design Pattern  Observer Design Pattern  Factory Design Pattern
  • 4. What is a Design Pattern ? 1. A problem that someone has already solved. 2. A model or design to use as a guide. 3. More formally: “A proven solution to a common problem in a specified context." Real World Examples: i. Blueprint for a house ii. Manufacturing
  • 5. Why Study Design Patterns? 1. Provides software developers a toolkit for handling problems that have already been solved. 2. Provides a vocabulary that can be used amongst software developers (The Pattern Name itself helps establish a vocabulary). 3. Helps you think about how to solve a software problem.
  • 6. The Gang of Four Defines a Catalog of different design patterns.  Three different types : I. Creational – “Creating objects in a manner suitable for the situation” II. Structural – “Ease the design by identifying a simple way to realize relationships between entities” III. Behavioral – “Common communication patterns between objects”
  • 7. The Gang of Four: 1. Creational 3. Behavioral Abstract Factory Chain of Responsibility Builder Command Factory Method Interpreter Prototype Iterator Singleton Mediator 2. Structural Memento Adapter Observer Bridge State Composite Strategy Decorator Template Method Façade Visitor Flyweight Proxy Patterns in Red we will discuss in this presentation !!
  • 9. Singleton Pattern 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.
  • 10. Singleton: Basic Structure Singleton - instance: Singleton - Singleton(); + getInstance(): Singleton
  • 12. Singleton Participants 1. Singleton a) Defines an Instance operation that lets clients access its unique instance. Instance is a class operation (static method). b) May be responsible for creating its own unique instance 2. Client a) Accesses a Singleton instance solely through the Singleton’s Instance() method.
  • 13. Singleton – Example 1) A status bar ….It could be implemented as a Singleton object, allowing only one instance and a focal point for updates. 2) One file system, one window manager, one printer spooler, one Test engine, one Input/output socket, Windows Registry etc.
  • 14. Singleton: Basic Implementation Class Singleton { private static Singleton unique Instance = null; private Singleton( ) { .. } // private constructor public static Singleton getInstance( ) { if (uniqueInstance == null) uniqueInstance = new Singleton(); // call constructor return uniqueInstance; } }
  • 15. Case Study  We want to create a remote connection to a server / database system and assure that only one connection is present. . Apply Singleton pattern
  • 16. Implementation : RemoteConnection Class RemoteConnection{ private static RemoteConnetion remoteConn; private RemoteConnection(){…} //private Constructor public static RemoteConnection getInstance(){ if( remoteConn == null ){ remoteConn = new RemoteConnection(); } return remoteConn; } }
  • 17. Lazy Instantiation 1) Objects are only created when it is needed. 2) Helps control that we’ve created the Singleton just once. 3) If it is resource intensive to set up, we want to do it once.
  • 18. Singleton Consequences: I. Controlled access to sole instance facilitates strict control over when and how the clients access it. II. The singleton patter is improvement over global variables. III. It is easy to configure an instance of the application that extends the functionality of singleton at run-time. IV. More flexible than class operations.
  • 19. Singleton Limitations: 1) The main limitation of the singleton pattern is that is permits the creation of only one instance of the class, while most practical applications require multiple instances to be initialized. 2) Furthermore, in case of singleton, the system threads fight to access the single instance thereby degrading the performance of the applications.
  • 21. Observer Pattern (Behavioral) Intent : Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Also Known As : Dependents, Publish-Subscribe, Delegation Event Model. 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.
  • 23. Participants in structure  Subject (interface): • Store the list of attached observers and provide operations for adding and removing the observer objects. • Expose an operation to notify all the attached observers  Observer (interface): • Defines an interface for updating mechanism.  ConcreteSubject: Get the update either from an external source or from any of the attached observer and notify the attached observers in case of change state.  ConcreteObserver: • Maintains a reference to a ConcreteSubject object. • Stores state that should stay consistent with the subject's. • Implements the Observer updating interface to keep its state consistent with the subject's
  • 24. Applying the Observer 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.
  • 25. A case study… In a university….when a student changes his address…pass this information to: a) Exams department b) Transport department. What's the solution?
  • 26. Applying observer to case study
  • 27. Implementation: Observer interface public interface myObserver { public void update(Student s); }
  • 28. Implementation: ExamDept class ExamDept implements myObserver { public void update(Student s){ System.out.println("Student Updated in Exam Dept"); System.out.println("New Address: "+ s.getAddress()); } }
  • 29. Implementation: TransportDept class TransportDept implements myObserver { public void update(Student s) { System.out.println("Student Updated in TD"); System.out.println("New Address: "+s.getAddress()); } }
  • 30. Implementation: Student 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(); } }
  • 31. Implementation: Main 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 (); }}
  • 32. Real Life Example Auctions: “Auctions demonstrate this pattern. Each bidder possesses a numbered paddle that is used to indicate a bid. The auctioneer starts the bidding, and "observes" when a paddle is raised to accept the bid. The acceptance of the bid changes the bid price which is broadcast to all of the bidders in the form of a new bid”
  • 33. Pros & Cons Pros : i. Decoupling of subject and observer, each can be extended and reused individually. ii. Dynamic addition and removal of observers at runtime. iii. Subject broadcasts notification automatically to all interested objects, no matter how many or which kind of observers are registered. Cons : i. May result in many notifications the observers are not interested in ii. Potentially difficult for the observers to figure out the specific state change of the subject.
  • 35. Factory- Creational Pattern Intent: “Define an interface for creating an object, but let subclasses decide which class to instantiate” Also Known as Virtual Constructor.
  • 36. Problem: “A framework needs to standardize the architectural model for a range of applications, but allow for individual applications to define their own domain objects and provide for their instantiation”
  • 37. Solution:  Factory Method Pattern offer a solution. It encapsulates the knowledge of which Document subclass to create and moves this knowledge out of the framework.  Application subclasses redefine an abstract CreateDocument( ) on Application to return an appropriate Document subclass.  Once an application subclass is instantiated , It can then instantiate application – specific Documents without knowing their Class , We call CreateDocument( ) a Factory Method because it is responsible for manufacturing an object.
  • 39. Participants:  Product( IHttpHandler) . Defines the interface of objects the factory method creates.  ConcreteProduct ( ASP.SamplePage_aspx ) . Implements the Product Interface.  Creator ( IHttpHandlerFactory ) . Declares the factory method and may provide a default implementation for it. . It returns an object of type Product.  ConcreteCreator( PageHandlerFactory ) . Overrides the factory method to return an instance of ConcreteProduct.
  • 40. Implementation:  Two major varieties: 1. Abstract Creator class with no default implementation 2. Concrete Creator with default implementation.  Solutions: 1. Parameterized Methods 2. Templates
  • 41. Parameterized Factory Method: class Creator { public: virtual Product* Create( ProductID id ) { if (id == P1) return new MyProduct ; if (id == P2) return new YourProduct; // other products ... return 0; }}; // You can subclass the Creator to handle more IDs Product* MyCreator::Create(ProductID id) { if (id == P3) return new TheirProduct; // Handle other IDs return this->Creator::Create(id); };
  • 42. Templatized Factory Methods: class Creator { public: Creator() { // You cannot call the factory method here (why?) // Use lazy initialization instead } virtual Product* CreateProduct() = 0; }; template <class T> class StandardCreator: public Creator { public: virtual Product* CreateProduct() { return new T; }} // In the Client StandardCreator<MyProduct> myCreator
  • 43. Consequences: I. The code deals with only with the product interface, therefore it can work with any user defined Concrete Product classes (decoupling subclass details from client classes). II. New concrete classes can be added without recompiling the existing code. III. It may lead to many subclasses if the product objects requires one or more additional objects. (Parallel class hierarchy)
  • 44. Known Uses: I. It is a very pervasive pattern. II. It is used in several places in the Java API. For example, URLConnection has a method getContent that returns the content as an appropriate object (html, gif etc.) III. FCL ( .Net Framework Class Library) is no exception to the use of Factory Method Pattern. For example, it is used in Systems.Collections.IEnumerable, System.Net.WebRequest, System.Security.Cryptography
  • 45. Real Life Example: Hotel: “One good example for the Factory Method is the Hotel. When Check in, the person gets the key from the front desk where he can be looked up as the ‘room’ factory. Now if he wants to make a phone call to some outside office, he will contact the front desk to make the connection to that call which means the front desk is acting as an interface.”
  • 46. But….. This presentation could not be completed without… The sources of information: 1. http://www.dofactory.com/Patterns/PatternObserver.aspx 2. http://www.vincehuston.org/dp/observer.html 3. http://en.wikipedia.org/wiki/Design_pattern 4. http://sourcemaking.com/design_patterns 5. Design Patterns: Elements of Reusable Object-oriented Software, by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, 1995 – “Gang of Four”. 6. Design Patterns in Ruby – Russ Olsen 7. Head First Design Patterns – Elisabeth Freeman, Eric Freeman, Bert Bates and Kathy Sierra 8. Special Thanks to Dr. Masroor Bhatti for providing us the chance to speak on Design Patterns.