62
Boutique product development company It is amazing what you can accomplish when you have a client-centric team to deliver outstanding products.

Software Desing Patterns

  • Upload
    confiz

  • View
    131

  • Download
    4

Embed Size (px)

DESCRIPTION

This tech-session cover software design patterns, type, details, intents, structure and sample code. In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations. Patterns are formalized best practices that the programmer must implement in the application. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.

Citation preview

Page 1: Software Desing Patterns

Boutique product development company It is amazing what you can accomplish when you have a client-centric team to deliver outstanding products.

Page 2: Software Desing Patterns

Design Patterns Arslan Anwar | Senior Software Engineer

Amir qayyum | Software Engineer

Page 3: Software Desing Patterns

Programs must be written for people to read, and only incidentally for machines to execute.

Design Patterns

➢ What are design patterns

➢ Why to use design patterns

➢ Type and Details of design patterns

➢ Design Pattern structure

➢ Code Examples

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 4: Software Desing Patterns

Design Patterns

What are design patterns

➢Design patterns are optimized, reusable solutions to the programming

problems that we encounter every day.

➢A design pattern is a well described solution to a common software

problem.

➢It is a template that has to be implemented in the correct situation.

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 5: Software Desing Patterns

Design Patterns

Benefits of Design Patterns

➢Design Patterns are already defined and provides industry

standard approach to solve a recurring problem, so it saves time if we

sensibly use the design pattern.

➢Using design patterns promotes reusability that leads to

more robust and highly maintainable code. It helps in reducing total

cost of ownership (TCO) of the software product.

➢ Since design patterns are already defined, it makes our code easy to

understand and debug. It leads to faster development and new members

of team understand it easily.

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 6: Software Desing Patterns

Design Patterns

Design Patterns Categories

Java Design Patterns are divided into three categories

Creational Structural Behavioral

Factory Method Abstract Factory Builder Prototype Singleton

Adapter Bridge Composite Decorator Flyweight Facade Proxy

Interpreter Template Method Chain of Responsibility Command Iterator Mediator Memento Observer State Strategy Visitor

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 7: Software Desing Patterns

Design Patterns

➢Singleton is a part of Gang of Four design pattern and it is

categorized under creational design patterns. In this article we are going

to take a deeper look into the usage of the Singleton pattern. It is one of

the most simple design pattern in terms of the modelling but on the

other hand this is one of the most controversial pattern in terms of

complexity of usage.

Singleton Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 8: Software Desing Patterns

Design Patterns

✓Ensure a class has only one instance, and provide a global point of

access to it.

✓Encapsulated "just-in-time initialization" or "initialization on first

use".

Singleton Design Pattern

Arslan Anwar | Senior Software Engineer , Amir D | Software Engineer

Page 9: Software Desing Patterns

Design Patterns

➢Structure

Singleton Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 10: Software Desing Patterns

Design Patterns

✓Abstract Factory, Builder, and Prototype can use Singleton in their

implementation.

✓Facade objects are often Singletons because only one Facade object is

required.

✓State objects are often Singletons.

✓The advantage of Singleton over global variables is that you are

absolutely sure of the number of instances when you use Singleton, and,

you can change your mind and manage any number of instances.

✓The Singleton design pattern is one of the most inappropriately used

patterns. Singletons are intended to be used when a class must have

exactly one instance, no more, no less. Designers frequently use

Singletons in a misguided attempt to replace global variables.

Singleton Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 11: Software Desing Patterns

Design Patterns

➢ Use in JDK

➢java.lang.Runtime#getRuntime()

➢java.awt.Desktop#getDesktop()

Example

Singleton Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 12: Software Desing Patterns

Design Patterns

➢Create a resource a share it inside your application? What will you

do?

➢Updating shared resource(s) by various users!

➢Only readable resource

Singleton Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 13: Software Desing Patterns

Design Patterns

The builder pattern is an object creation software design pattern. The

intention of the builder pattern is to find a solution to the telescoping

constructor anti-pattern.

The telescoping constructor anti-pattern occurs when the increase of

object constructor parameter combination leads to an exponential list of

constructors.

Instead of using numerous constructors, the builder pattern uses another

object, a builder, that receives each initialization parameter step by step

and then returns the resulting constructed object at once.

Builder Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 14: Software Desing Patterns

Design Patterns

Builder Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 15: Software Desing Patterns

Design Patterns

The intent of the Builder design pattern is to separate the construction of

a complex object from its representation. By doing so, the same

construction process can create different representations

For constructor management. For example google protocol buffer is a

way to transport objects. So we need a Template to make agreement on

both sides that we are sending an object with a specific structure.

Builder Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 16: Software Desing Patterns

Design Patterns

Large class with multiple constructors and u need a constructor

constructor?

What if you have constructors, some setting some data and some setting

other data make some data null or modifying it?

Setting data in object in meaningful manner. Because we know setter

provide more meaning in setting/assigning a value to a property. OK?

Builder Design Pattern exercise

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 17: Software Desing Patterns

Design Patterns

Deals with the problem of creating objects (products) without

specifying the exact class of object that will be created. The essence of

this pattern is to "Define an interface for creating an object, but let the

classes that implement the interface decide which class to instantiate.

The Factory method lets a class defer instantiation to subclasses.

If object creation code is spread in whole application, and if you need to

change the process of object creation then you need to go in each and

every place to make necessary changes.

Factory method Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 18: Software Desing Patterns

Design Patterns

Factory method Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 19: Software Desing Patterns

Design Patterns

➢The creation of an object precludes its reuse without significant

duplication of code.

➢The creation of an object requires access to information or resources

that should not be contained within the composing class.

➢The lifetime management of the generated objects must be

centralized to ensure a consistent behavior within the application.

Factory method Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 20: Software Desing Patterns

Design Patterns

What will you do if your applications is consuming services that are

hosted on different servers for Work, QA and End users.

What you do to handle object creation of some interface or parent class

that you are using on different levels in application.

Factory method Design Pattern exercise

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 21: Software Desing Patterns

Design Patterns

The Abstract Factory is known as a creational pattern - it's used to

construct objects such that they can be decoupled from the

implementing system. The definition of Abstract Factory provided in

the original Gang of Four book on Design Patterns states:

“Provides an interface for creating families of related or dependent

objects without specifying their concrete classes.”

Abstract Factory Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 22: Software Desing Patterns

Design Patterns

➢With the Factory pattern, you produce implementations (Apple,

Banana, Cherry, etc.) of a particular interface -- say, IFruit.

➢With the Abstract Factory pattern, you produce implementations of a

particular Factory interface -- e.g., IFruitFactory. Each of those knows

how to create different kinds of fruit.

How different from Factory Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 23: Software Desing Patterns

Design Patterns

Abstract Factory Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 24: Software Desing Patterns

Design Patterns

➢ The client code has no knowledge whatsoever of the concrete type.

The client code deals only with the abstract type. Objects of a concrete

type are indeed created by the factory, but the client code accesses such

objects only through their abstract interface.

➢ Adding new concrete types is done by modifying the client code to

use a different factory, a modification that is typically one line in one

file.

➢The different factory then creates objects of a different concrete type,

but still returns a pointer of the same abstract type as before — thus

insulating the client code from change.

Abstract Factory Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 25: Software Desing Patterns

Design Patterns

➢There will be a single Abstract Factory class (or interface) with two

concrete subclasses (cool and uncool).

➢The Abstract Factory class will contain three abstract methods with

no bodies.

➢For each product (A, B and C) there'll be an interface plus two

concrete subclasses.

➢The main program should create the factory instance that is used in

the program, and this should be passed to the Client class to tell it if

it should create cool or uncool products.

Abstract Factory Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 26: Software Desing Patterns

Design Patterns

It is used when the type of objects to create is determined by a

prototypical instance, which is cloned to produce new objects. This

pattern is used to:

– Avoid subclasses of an object creator in the client application, like

the abstract factory pattern does.

– Avoid the inherent cost of creating a new object in the standard

way (e.g., using the 'new' keyword) when it is prohibitively

expensive for a given application.

To implement the pattern, declare an abstract base class that specifies a

pure virtual clone() method. Any class that needs a "polymorphic

constructor" capability derives itself from the abstract base class, and

implements the clone() operation.

Prototype Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 27: Software Desing Patterns

Design Patterns

Prototype Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 28: Software Desing Patterns

Design Patterns

The client, instead of writing code that invokes the "new" operator on a

hard-coded class name, calls the clone() method on the prototype, calls

a factory method with a parameter designating the particular concrete

derived class desired, or invokes the clone() method through some

mechanism provided by another design pattern.

Prototype Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 29: Software Desing Patterns

Design Patterns

You are working on a editor with no ability of refactoring and you need to change

name of class what will you do. How can you use prototype pattern will help you

in that?

Prototype Design Pattern exercise

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 30: Software Desing Patterns

Design Patterns

Chain Of Responsibility

➢ Avoid coupling the sender of a request to the receiver by giving

more than one object a chance to handle the request. Chain the

receiving objects and pass the request along the chain until an object

handles it.

➢The main intention in Chain Of Responsibility is to decouple the

origin of the request and the handling of the request such that the origin

of the request need not worry who and how its request is being handled

as long as it gets the expected outcome

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 31: Software Desing Patterns

Design Patterns

Chain Of Responsibility

➢Intent

○ The main intention in Chain Of Responsibility is to decouple the

origin of the request and the handling of the request such that the

origin of the request need not worry who and how its request is

being handled as long as it gets the expected outcome

○ Sender will not know which object in the chain will serve its

request.

○ Every node in chain will have the responsibility to decide, if they

can serve the request.

○ If node decides to forward the request, it should be capable of

choosing the next node and forward it.

○ There is a possibility where none of the node may serve the request

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 32: Software Desing Patterns

Design Patterns

Chain Of Responsibility

➢ Structure

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 33: Software Desing Patterns

Design Patterns

Chain Of Responsibility

➢ Use in JDK

javax.servlet.Filter#doFilter()

java.util.logging.Logger#log

Ads by Google

➢ Example

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 34: Software Desing Patterns

Design Patterns

Observer

➢ In observer design pattern multiple observer objects registers with a

subject for change notification. When the state of subject changes, it

notifies the observers. Objects that listen or watch for change are called

observers and the object that is being watched for is called subject.

➢Pattern involved is also called as publish-subscribe pattern. Model

view controller (MVC) architecture’s core uses the observer design

pattern.

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 35: Software Desing Patterns

Design Patterns

✓Subject provides interface for observers to register and unregister

themselves with the subject.

✓Subject knows who its subscribers are.

✓Multiple observers can subscribe for notifications.

✓Subject publishes the notifications.

✓Subject sends the notification saying the state has changed. It can

also pass any state information.

Observer

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 36: Software Desing Patterns

Design Patterns

➢ Structure

Observer

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 37: Software Desing Patterns

Design Patterns

➢ Use in JDK

HttpSessionBindingListener is an example where Observer design

pattern in used in Java API.

Example

Observer

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 38: Software Desing Patterns

Design Patterns

Command Design Pattern

➢Command design pattern is used to encapsulate a request as an object

and pass to an invoker, wherein the invoker does not knows how to

service the request but uses the encapsulated command to perform an

action.

➢To understand command design pattern we should understand the

associated key terms like client, command, command implementation,

invoker, receiver.

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 39: Software Desing Patterns

Design Patterns

✓Command is an interface with execute method. It is the core of

contract.

✓A client creates an instance of a command implementation and

associates it with a receiver.

✓An invoker instructs the command to perform an action.

✓A Command implementation’s instance creates a binding between the

receiver and an action.

✓Receiver is the object that knows the actual steps to perform the

action.

Command Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 40: Software Desing Patterns

Design Patterns

✓Command pattern helps to decouple the invoker and the receiver.

Receiver is the one which knows how to perform an action.

✓Command helps to implement call back in java.

✓Helps in terms of extensibility as we can add new command without

changing existing code.

✓Command defines the binding between receiver and action.

✓A command should be able to implement undo and redo operations.

That is restting the state of the receiver. It can be done from the support

of receiver.

Command Design Pattern (Important Points)

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 41: Software Desing Patterns

Design Patterns

➢ Structure

Command Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 42: Software Desing Patterns

Design Patterns

➢ Use in JDK

Implementations of java.lang.Runnable and javax.swing.Action follows

command design pattern.

Example

Command Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 43: Software Desing Patterns

Design Patterns

➢Template method pattern is a behavioral design pattern which

provide base method for algorithm,called template method which defers

some of its steps to subclasses So algorithm structure is same but some

of its steps can be redefined by subclasses according to context.

➢To understand command design pattern we should understand the

associated key terms like client, command, command implementation,

invoker, receiver.

Template Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 44: Software Desing Patterns

Design Patterns

✓Template method in super class follows “the Hollywood principle”:

“Don’t call us, we’ll call you”. This refers to the fact that instead of

calling the methods from base class in the subclasses, the methods from

subclass are called in the template method from superclass.

✓Template method in super class should not be overridden so make it

final

✓Template methods are technique for code reuse because with this,you

can figure out common behavior and defer specific behavior to

subclasses.

Template Design Pattern (Important Points)

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 45: Software Desing Patterns

Design Patterns

✓ Define the skeleton of an algorithm in an operation, deferring some

steps to subclasses.

✓ Template Method lets subclasses redefine certain steps of an

algorithm without letting them to change the algorithm's structure.

Template Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 46: Software Desing Patterns

Design Patterns

➢ Structure

Template Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 47: Software Desing Patterns

Design Patterns

➢ Use in JDK

➢All non-abstract methods of java.io.InputStream,

java.io.OutputStream, java.io.Reader and java.io.Writer.

➢All non-abstract methods of java.util.AbstractList,

java.util.AbstractSet and java.util.AbstractMap.

➢javax.servlet.http.HttpServlet, all the doXXX() methods by default

sends a HTTP 405 "Method Not Allowed" error to the response. You're

free to implement none or any of them.

Example

Template Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 48: Software Desing Patterns

Design Patterns

➢Visitor Pattern is one of the behavioral design pattern. Visitor

pattern is used when we have to perform an operation on a group of

similar kind of Objects. With the help of visitor pattern, we can move

the operational logic from the objects to another class.

➢For example, think of a Shopping cart where we can add different

type of items (Elements), when we click on checkout button, it

calculates the total amount to be paid. Now we can have the calculation

logic in item classes or we can move out this logic to another class

using visitor pattern. Let’s implement this in our example of visitor

pattern.

Visitor Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 49: Software Desing Patterns

Design Patterns

✓Represent an operation to be performed on the elements of an object

structure. Visitor lets you define a new operation without changing the

classes of the elements on which it operates.

✓The classic technique for recovering lost type information.

✓Do the right thing based on the type of two objects.

✓Double dispatch

Visitor Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 50: Software Desing Patterns

Design Patterns

➢ Structure

Visitor Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 51: Software Desing Patterns

Design Patterns

✓The benefit of this pattern is that if the logic of operation changes,

then we need to make change only in the visitor implementation rather

than doing it in all the item classes.

✓Another benefit is that adding a new item to the system is easy, it will

require change only in visitor interface and implementation and existing

item classes will not be affected.

✓The drawback of visitor pattern is that we should know the return

type of visit() methods at the time of designing otherwise we will have

to change the interface and all of its implementations. Another

drawback is that if there are too many implementations of visitor

interface, it makes it hard to extend.

Visitor Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 52: Software Desing Patterns

Design Patterns

➢ Use in JDK

➢javax.lang.model.element.AnnotationValue and

AnnotationValueVisitor

➢javax.lang.model.element.Element and ElementVisitor

➢javax.lang.model.type.TypeMirror and TypeVisitor

Example

Visitor Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 53: Software Desing Patterns

Design Patterns

➢Strategy pattern is one of the behavioral design pattern. Strategy

pattern is used when we have multiple algorithm for a specific task and

client decides the actual implementation to be used at runtime.

➢Strategy pattern is also known as Policy Pattern. We defines

multiple algorithms and let client application pass the algorithm to be

used as a parameter. One of the best example of this pattern

is Collections.sort() method that takes Comparator parameter. Based on

the different implementations of Comparator interfaces, the Objects are

getting sorted in different ways.

Strategy Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 54: Software Desing Patterns

Design Patterns

✓Define a family of algorithms, encapsulate each one, and make them

interchangeable. Strategy lets the algorithm vary independently from

the clients that use it.

✓Capture the abstraction in an interface, bury implementation details in

derived classes.

Strategy Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 55: Software Desing Patterns

Design Patterns

➢ Structure

Strategy Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 56: Software Desing Patterns

Design Patterns

✓We could have used composition to create instance variable for

strategies but we should avoid that as we want the specific strategy to

be applied for a particular task, same is followed in Collections.sort()

and Arrays.sort() method that take comparator as argument.

✓Strategy Pattern is very similar to State Pattern. One of the difference

is that Context contains state as instance variable and there can be

multiple tasks whose implementation can be dependent on the state

whereas in strategy pattern strategy is passed as argument to the method

and context object doesn’t have any variable to store it.

✓Strategy pattern is useful when we have multiple algorithms for

specific task and we want our application to be flexible to chose any of

the algorithm at runtime for specific task.

Strategy Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 57: Software Desing Patterns

Design Patterns

➢ Use in JDK

➢java.util.Comparator#compare(), executed by among others

Collections#sort().

➢javax.servlet.http.HttpServlet, the service() and all doXXX() methods

take HttpServletRequest and HttpServletResponse and the implementor

has to process them (and not to get hold of them as instance variables!).

➢javax.servlet.Filter#doFilter()

Example

Strategy Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 58: Software Desing Patterns

Design Patterns

➢State pattern is one of the behavioral design pattern. State design

pattern is used when an Object change it’s behavior based on it’s

internal state.

➢If we have to change the behavior of an object based on it’s state, we

can have a state variable in the Object and use if-else condition block to

perform different actions based on the state.

State Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 59: Software Desing Patterns

Design Patterns

✓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

✓wrapper + polymorphic wrappee + collaboration

State Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 60: Software Desing Patterns

Design Patterns

➢Structure

State Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 61: Software Desing Patterns

Design Patterns

✓The benefits of using State pattern to implement polymorphic

behavior is clearly visible, the chances of error are less and it’s very

easy to add more states for additional behavior making it more robust,

easily maintainable and flexible. Also State pattern helped in avoiding

if-else or switch-case conditional logic in this scenario

✓The implementation of the State pattern builds on the Strategy

pattern. The difference between State and Strategy is in the intent. With

Strategy, the choice of algorithm is fairly stable. With State, a change in

the state of the "context" object causes it to select from its "palette" of

Strategy objects.

State Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer

Page 62: Software Desing Patterns

Design Patterns

➢Use in JDK

➢javax.faces.lifecycle.LifeCycle#execute() (controlled by

FacesServlet, the behaviour is dependent on current phase (state) of JSF

lifecycle)

Example

State Design Pattern

Arslan Anwar | Senior Software Engineer , Amir qayyum | Software Engineer