Dr. Rania Khairy Software Engineering and Development Tool
Design Patterns
Dr. Rania Khairy Software Engineering and Development Tool
What are Design Patterns?
Dr. Rania Khairy Software Engineering and Development Tool
What are Design Patterns?
Dr. Rania Khairy Software Engineering and Development Tool
Why Patterns?
Dr. Rania Khairy Software Engineering and Development Tool
Canonical Cataloging
• Other Design Patterns Books:
– Freeman, Eric and Elisabeth Freeman with Kathy Sierra and Bert Bates. Head First Design Patterns. Sebastopol, CA: O'Reilly, 2004.
– John Dooley, Software Development and Professional Practice
– Timothy C. Lethbridge and Robert Laganière, “Object-Oriented Software Engineering: Practical Software Development using UML and Java”, Second Edition, McGraw Hill 2001
Dr. Rania Khairy Software Engineering and Development Tool
Classifying Design Pattern
Dr. Rania Khairy Software Engineering and Development Tool
The Gang of Four Catalog Method
Dr. Rania Khairy Software Engineering and Development Tool
Types of Design Patterns
• Creational Design Patterns
– Singleton Pattern
– Factory Pattern
– Abstract Factory Pattern
– Builder Pattern
– Prototype Pattern
• Structural Design Patterns
– Adapter Pattern
– Composite Pattern
– Proxy Pattern
– Flyweight Pattern
– Facade Pattern
– Bridge Pattern
– Decorator Pattern
• Behavioral Design Patterns
– Template Method Pattern
– Mediator Pattern
– Chain of Responsibility Pattern
– Observer Pattern
– Strategy Pattern
– Command Pattern
– State Pattern
– Visitor Pattern
– Iterator Pattern
– Memento Pattern
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
How do I use design patterns?
Dr. Rania Khairy Software Engineering and Development Tool
How do I use design patterns?
Dr. Rania Khairy Software Engineering and Development Tool
1. Singleton Pattern
• Intent:
– Ensure a class has only one instance, and provide a global point of access to that instance.
– Encapsulated "just-in-time initialization" or "initialization on first use“.
• Problem: Application needs one, and only one, instance of an object. Additionally, lazy initialization and global access are necessary.
• When to use?
– Examples: manage thread pools, caches, registry and preference settings, logging objects, device drivers objects (printers and graphics cards).
– More than one instance, cause problems like incorrect program behaviour, overuse of resources, or inconsistent results.
Dr. Rania Khairy Software Engineering and Development Tool
1. Singleton Pattern
• Structure:
– Define a private static attribute, often called theInstance. This stores the single instance
– Define a public static accessor function, often called getInstance. The first time this method is called, it creates the single instance and stores it in theInstance.
– Define private constructor to ensure that no other class will be able to create an instance of the singleton class
– Clients may only use the accessor function to manipulate the Singleton
Dr. Rania Khairy Software Engineering and Development Tool
Example of Singleton Pattern
Dr. Rania Khairy Software Engineering and Development Tool
Example of Singleton Pattern
Dr. Rania Khairy Software Engineering and Development Tool
2. Factory Pattern • The factory pattern (also known as the factory method pattern) is a
creational design pattern.
• Intent: Define an interface for creating an object, but let subclasses decide which class to instantiate
• 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.
• When to use? A factory is used to encapsulate object creation code. A factory class instantiates and returns a particular type of object based on data passed to the factory. The different types of objects that are returned from a factory typically are subclasses of a common parent class.
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Example of Factory Pattern
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Output
Dr. Rania Khairy Software Engineering and Development Tool
3. Observer Pattern
• The observer pattern is a behavioral object design pattern.
• Intent:
– Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
– Encapsulate the core (or common or engine) components in a Subject abstraction, and the variable (or optional or user interface) components in an Observer hierarchy.
Dr. Rania Khairy Software Engineering and Development Tool
3. Observer Pattern
• Structure
– Define an object that is the "keeper" of the data model and/or business logic (the Subject). Delegate all "view" functionality to decoupled and distinct Observer objects.
– Observers register themselves with the Subject as they are created.
– Whenever the Subject changes, it broadcasts to all registered Observers that it has changed, and each Observer queries the Subject for that subset of the Subject's state that it is responsible for monitoring.
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Example of Observer Pattern
• Example
– 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.
Dr. Rania Khairy Software Engineering and Development Tool
Observer Pattern in Action
• Observer pattern uses three actor classes. Subject, Observer and Client.
• Subject has methods to attach and detach observers to a client object.
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
4. State Pattern
• The state pattern is a behavioral object design pattern.
• Intent :
– Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
– An object-oriented state machine.
• When to use?
– The State pattern is a solution to the problem of how to make behavior depend on state.
– The state pattern avoids the use of switch and if statements to change behavior.
Dr. Rania Khairy Software Engineering and Development Tool
4. State Pattern
• Structure:
– Define a "context" class to present a single interface to the outside world.
– Define a State abstract base class.
– Represent the different "states" of the state machine as derived classes of the State base class.
– Define state-specific behavior in the appropriate State derived classes.
– Maintain a pointer to the current "state" in the "context" class.
– To change the state of the state machine, change the current "state" pointer.
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Example of State Pattern Example:
This pattern can be observed in a vending machine. Vending machines have states based on the inventory, amount of currency deposited, the ability to make change, the item selected, etc. When currency is deposited and a selection is made, a vending machine will either deliver a product and no change, deliver a product and change, deliver no product due to insufficient currency on deposit, or deliver no product due to inventory depletion.
Dr. Rania Khairy Software Engineering and Development Tool
State Pattern Example 1
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
State Pattern Example 2
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
5. Decorator Pattern
• The decorator pattern is a structural design pattern.
• Intent
– Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
– You want to add behavior or state to individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class.
• When to use?
– the decorator pattern adds functionality to objects by wrapping objects in other objects. Each time additional functionality is required, the object is wrapped in another object. Java I/O streams are a well-known example of the decorator pattern.
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Decorator Pattern Example
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
6. Adapter Pattern
• The adapter pattern is a structural design pattern
• Intent
– Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
– Wrap an existing class with a new interface.
• Structure:
– This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces.
– A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. You plugin the memory card into card reader and card reader into the laptop so that memory card can be read via laptop..
Dr. Rania Khairy Software Engineering and Development Tool
6. Adapter Pattern • When to use?
– Adapter is about creating an intermediary abstraction that translates, or maps, the old component to the new system. Clients call methods on the Adapter object which redirects them into calls to the legacy component. This strategy can be implemented either with inheritance or with aggregation.
– Adapter functions as a wrapper or modifier of an existing class. It provides a different or translated view of that class.
Dr. Rania Khairy Software Engineering and Development Tool
Adapter Pattern Example
• We have a MediaPlayer interface and a concrete class AudioPlayer implementing the MediaPlayer interface. AudioPlayer can play mp3 format audio files by default.
• We are having another interface AdvancedMediaPlayer and concrete classes implementing the AdvancedMediaPlayer interface. These classes can play vlc and mp4 format files.
• We want to make AudioPlayer to play other formats as well. To attain this, we have created an adapter class MediaAdapter which implements the MediaPlayer interface and uses AdvancedMediaPlayer objects to play the required format.
• AudioPlayer uses the adapter class MediaAdapter passing it the desired audio type without knowing the actual class which can play the desired format. AdapterPatternDemo, our demo class will use AudioPlayer class to play various formats.
Dr. Rania Khairy Software Engineering and Development Tool
Adapter Pattern Example
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Adapter vs Decorator
• Adapter is meant to change the interface of an existing object.
• Decorator enhances another object without changing its interface.
• Decorator is thus more transparent to the application than an adapter is.
• As a consequence, Decorator supports recursive composition, which isn't possible with pure Adapters.
Dr. Rania Khairy Software Engineering and Development Tool
7. Façade Pattern
• The facade pattern is a structural design pattern.
• Intent
– Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
– Wrap a complicated subsystem with a simpler interface.
• Structure
– Identify a simpler, unified interface for the subsystem or component.
– Design a 'wrapper' class that encapsulates the subsystem.
– The facade/wrapper captures the complexity and collaborations of the component, and delegates to the appropriate methods.
– The client uses the Facade only.
Dr. Rania Khairy Software Engineering and Development Tool
Façade vs Adapter
• Facade defines a new interface, whereas Adapter uses an old interface. Remember that Adapter makes two existing interfaces work together as opposed to defining an entirely new one.
• Facade objects are often Singletons because only one Facade object is required.
• Adapter and Facade are both wrappers; but they are different kinds of wrappers. The intent of Facade is to produce a simpler interface, and the intent of Adapter is to design to an existing interface. While Facade routinely wraps multiple objects and Adapter wraps a single object; Facade could front-end a single complex object and Adapter could wrap several legacy objects.
Dr. Rania Khairy Software Engineering and Development Tool
Example of Façade Pattern
• We are going to create a Shape interface and concrete classes implementing the Shape interface. A facade class ShapeMaker is defined as a next step.
• ShapeMaker class uses the concrete classes to delegate user calls to these classes. FacadePatternDemo will use ShapeMaker class to show the results.
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
8. MVC Pattern
• MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application’s concerns.
• Model – Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes.
• View – View represents the visualization of the data that model contains.
• Controller – Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.
Dr. Rania Khairy Software Engineering and Development Tool
8. MVC Pattern We are going to create a Student object acting as a model. StudentView will be a view class which can print student details on console and StudentController is the controller class responsible to store data in Student object and update view StudentView accordingly. MVCPatternDemo will use StudentController to demonstrate use of MVC pattern.
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool
Dr. Rania Khairy Software Engineering and Development Tool