Design pattern-presentation
-
Upload
rana-muhammad-asif -
Category
Documents
-
view
37 -
download
0
Transcript of Design pattern-presentation
Professional Practices
Course Instructor : DR. Masroor Ahmed Bhatti
Design Pattern
Introduction Singleton, Observer & Factory Design
Pattern.
Group MembersI. 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 CommandFactory Method InterpreterPrototype IteratorSingleton Mediator
2. Structural MementoAdapter Observer Bridge StateComposite Strategy
Decorator Template Method Façade VisitorFlyweight Proxy
Patterns in Red we will discuss in this presentation !!
Singleton PatternIntent : 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 Participants1. 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
c) Accesses a Singleton instance solely through the Singleton’s Instance() method.
Singleton – Example1) 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 ImplementationClass 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
RemoteConnection
remoteConn : RemoteConnection
getInstance() : RemoteConnectionRemoteConnection()
Implementation : RemoteConnectionClass RemoteConnection{
private static RemoteConnetion remoteConn;private RemoteConnection(){…}
//private Constructor
public static RemoteConnection getInstance(){if( remoteConn == null ){
remoteConn = new RemoteConnection(); } return remoteConn;}}
Lazy Instantiation1) 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)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
ConcreteObserver
Observer
Update(s : Subject)
<<<Interface>>>Subject
ObserversList : Vector
register(Obs : myObserver)unRegister(Obs : myObserver)notify()
Notify lets all observers know that event has occured
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 ObserverStep 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
TransportDept ExamDept
myObserver
update(s : Student)
<<<Interface>>>
Student
address : StringmyObs : Vector
register(Obs : myObserver)unRegister(Obs : myObserver)notifyObs()changeAddress()getAddress()
Composition
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: TransportDeptclass TransportDept implements myObserver
{
public void update(Student s)
{
System.out.println("Student Updated in TD");
System.out.println("New Address: "+s.getAddress());
}
}
Implementation: Studentclass 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: Mainclass 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 ExampleAuctions:
“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 & ConsPros :
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 :
iv. May result in many notifications the observers are not interested in
v. Potentially difficult for the observers to figure out the specific state change of the subject.
Factory- Creational PatternIntent:
“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.
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 IDsProduct* 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.