90
Design Patterns Introduction

Design pattern part 1

Embed Size (px)

Citation preview

Design Patterns

Introduction

OriginsPatterns originated as an architectural concept by Christopher Alexander (1977) (Austria).

It was initially applied for architecture forbuildings and towns, But not computerprogramming for writing software.

‘‘Complexity is one of the great problem in environmental design’’.

“Each pattern describes a problem which occursover and over again in our environment, andthen describes the core of the solution to thatproblem, in such a way that you can use thissolution a million times over, without everdoing it the same way twice”

-Christopher Alexander (Architect)“A Pattern Language", New York,Oxford University Press, 1977

Origins (Continued)

In 1987, Kent Beck and Ward Cunningham began experimenting with the idea of applying patterns to programming.

Design patterns gained popularity in computer science after the book : Elements of Reusable Object-Oriented Software was published in 1994 by the so-called “Gang of Four” which is frequently abbreviated as "GoF"

Origins (Continued)

What is the difference between loose coupling and tight coupling ?

Tight coupling is when a group of classes are highly dependent on one another.

Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns.

A loosely-coupled class can be consumed and tested independently of other (concrete) classes.

Interfaces are a powerful tool to use for decoupling. Classes can communicate through interfaces rather than other concrete classes.

Avoid: Tight Coupling !

It might get you into trouble ..

Four Essential Parts

➔ Pattern nameA handle to briefly describe the design problem.

➔ ProblemA description of the problem that the design pattern is intended to solve.

➔ SolutionDescribes what elements are required to make up the design, their relationships and its context.

➔ ConsequencesWhat are the results and trade offs by applying the design pattern .

Types of Patterns➔ Creational Pattern

This design pattern is all about class instantiation

➔ Structural PatternThis design pattern is all about Class and Object composition.

➔ Behavioral PatternThis design pattern is all about Class's objects communication

Types of Patterns (Overview)Creational : Creational patterns are ones that create objects for you,rather than having you instantiate objects directly. This gives your program more flexibility in deciding which objects need to be created for a given case.

• Factory : Allow subclasses to “decide” which class to instantiate.• Abstract Factory : Creates an instance of several derived classes.• Builder : Separates object construction from its representation.• Prototype : Creates objects by cloning an existing object.• Singleton : A class of which only a single instance can exist.• Object Pool : Avoid expensive acquisition and release of resources by recycling objects that are no longer in use.

Factory Provide an interface for the creation of objects.

Allow subclasses to “decide” which class to instantiate.

When to useWhen the parent classes choose the creation of objects to its sub-classes.

When a class doesn't know what sub-classes will be required to create.

When a class wants that its sub-classes specify the objects to be created.

Factory ExampleHintNew shapes can be added without changing a single line of code in the framework.

Advantagesallows the sub-classes to choose the type of objects to create.

adding new products without even modifying the factory class.

It promotes the loose-coupling.

Abstract Factory Provide an interface for creating families of related or dependentobjects without specifying their concrete classes.

A class returns a factory of classes.

Abstract Factory Pattern is one level higher than the Factory Pattern.

When to useWhen the system needs to be independent of how its object are created.

When the family of related objects has to be used together, this constraint needs to be enforced.

Abstract Factory Example

AdvantagesIt promotes consistency among objects.

Pattern isolates the client code from implementation.

It eases the exchanging of object families.

BuilderBuilder pattern builds a complex object using simple objects and using a step by step approach.

This pattern provides one of the best ways to create an object

A Builder class builds the final object step by step. This builder is independent of other objects.

When to usewhen object can't be created in single step like in the de-serialization of a complex object.

Builder Example

AdvantagesIt supports to change the internal representation of objects.

It provides clear separation between the construction and representation of an object.

It provides better control over construction process.

SingletonEnsure a class has only one instance, and provide a global point ofaccess to it .

This pattern involves a single class which is responsible to create an object while making sure that only single object gets created.

Early Instantiation: creation of instance at load time.

Lazy Instantiation: creation of instance when required.

When to useSingleton pattern is mostly used in multi-threaded and database applications

It is used in logging, caching, thread pools, configuration settings.

Singleton Example

AdvantagesSaves memory because object is not created at each request

Only single instance is reused again and again.

Prototypecloning of an existing object instead of creating new one and can also be customized as per the requirement.

This pattern should be followed, if the cost of creating a new object is expensive and resource intensive.

When to useWhen the client application needs to be unaware of object creation and representation.

When the classes are instantiated at runtime.

When the cost of creating an object is expensive or complicated.

Prototype Example Hint

an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.

AdvantagesIt lets you add or remove objects at runtime.

It reduces the need of sub-classing.

It hides complexities of creating objects.

Object PoolAvoid expensive acquisition and release of resources by recyclingobjects that are no longer in use.

Objects in the pool have a lifecycle: creation, validation and destroy.

While the Prototype pattern helps in improving the performance by cloning the objects, the Object Pool pattern offers a mechanism to reuse objects that are expensive to create. 

When to useWhen there are several clients who need the same resource at different times.

Database connections.(too many connections )

When an application requires objects which are expensive to create.

Object Pool Example Hint

Object pool design pattern is essentially used in Web Container of the server for creating thread pools and data source pools to process the requests..

AdvantagesIt boosts the performance of the application significantly.

It can also limit the maximum number of objects that can be created.

It manages the connections and provides a way to reuse and share them.

Types of Patterns (Overview)Structural: Structural design patterns are concerned with how classes and objects can be composed to form larger structures.These patterns focus on how the classes inherit from each other and how they are composed from other classes.

• Adapter: Match interfaces of different classes.• Bridge: Separates an object’s interface from its implementation.• Composite: : A tree structure of simple and composite objects.• Decorator: Add responsibilities to objects dynamically.• Facade: A single class that represents an entire subsystem.• Flyweight : A fine-grained instance used for efficient sharing.• Proxy : An object representing another object.

AdapterConverts the interface of a class into another interface that a client wants.

Can you imagine a situation when you have some class expecting some type of object and you have an object offering the same features, but exposing a different interface?

When to useWhen an object needs to utilize an existing class with an incompatible interface.

When you want to create a reusable class that cooperates with classes which don't have compatible interfaces.

Adapter Example

AdvantagesIt allows two or more previously incompatible objects to interact.

It allows reusability of existing functionality.

Bridge Decouple an abstraction from its implementation so that the two canvary independently.

When to usewhere changes are made in the implementation does not affect the clients.

When you don't want a permanent binding between the functional abstraction and its implementation.

When both the functional abstraction and its implementation need to extended using sub-classes.

Bridge ExampleHintFor example GUI frameworks separate a Window abstraction from a Window implementation for Linux or Mac OS using the bridge pattern.

HintAdapter makes things work after they're designed.Bridge makesthem work before they are .

AdvantagesIt allows the hiding of implementation details from the client.

It enables the separation of implementation from the interface.

It improves the extensibility.

Composite Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy.

This Pattern creates a tree structure of group of objects.

When to useWhere the responsibility of object may vary from time to time.

When you want to represent a full or partial hierarchy of objects.

When the responsibilities are needed to be added dynamically to the individual objects without affecting other objects.

Composite Example

HintGraphics Editors use composite pattern to implement complex and simple graphics .

HintFile System implementations use the composite design pattern.

Code Example

Output

AdvantagesIt provides flexibility of structure with manageable class or interface.

It defines class hierarchies that contain primitive and complex objects.

It makes easier to you to add new kinds of components.

DecoratorExtending an object’s functionality can be done statically (at compile time) by using inheritance however it might be necessary to extend an object’s functionality dynamically (at runtime) as an object is used.

The Decorator Pattern uses composition instead of inheritance to extend the functionality of an object at runtime.

When to useExtending functionality by sub-classing is no longer practical.

When you want to transparently and dynamically add responsibilities to objects without affecting other objects.

When you want to add responsibilities to an object that you may want to change in future.

Decorator Example Hint

Graphical User Interface Frameworks uses Decorator.

HintEx: Pizza . Addition ( Mozzarella – Chicken , …etc. )

AdvantagesIt simplifies the coding by allowing you to develop a series of functionality from targeted classes instead of coding all of the behavior into the object.

It provides greater flexibility than static inheritance.

It enhances the extensibility of the object.

HintDecoration adds functionality to objects at runtime which would make debugging system functionality harder.

Facade Provide a general (simpler) interface for a set of interfaces to hide complexity of the System.

When to useWhen you want to provide simple interface to a complex sub-system

When several dependencies exist between clients and the implementation classes of an abstraction

Facade ExampleHintEvery Abstract Factory is a type of Facade

HintCan I withdrawal $50 from the bank ?1. check If the checking account is valid ! 2. check if the security code is valid !3. check if funds are available !

AdvantagesIt shields the clients from the complexities of the sub-system components.

It promotes loose coupling between subsystems and its clients.

FlyweightUse one instance of a class to provide many “virtual” instances.

This Pattern tries to reuse already existing similar kind objects by storing them and creates new object when no matching object is found.

When to useWhen the application does not depend on object identity.

When an application uses large number of objects.

When the storage cost is high because of the quantity of objects.

Flyweight Example Hint

Game of war .Large number of Soldiers . text editors.

AdvantagesIt reduces the number of objects.

It reduces the amount of memory and storage devices required if the objects are persisted.

Proxy (Placeholder)Proxy means an object representing another object.

Provides the control for accessing the original object.

When to useIf we need to use only a few methods of some costly objects.we can use some light objects exposing the same interface as the heavy objects.

Proxy scenarios

Smart ProxyA smart proxy provides additional layer of security by interposing specific actions when the object is accessed.Ex: to check whether the real object is locked or not before accessing it.

Remote Proxyprovides a local representation of the object which is present in the different address location.Ex: web service or REST resources.

Protective Proxy It acts as an authorization layer to verify that whether the actual user has access the appropriate content or not.

Virtual ProxyConsider a situation where there is multiple database call to extract huge size image.

Proxy ExampleHintATM Machine

HintThe Java Remote Method Invocation (RMI) system allows an object running in one Java virtual machine to invoke methods on an object running in another Java virtual machine.

Code Example

AdvantagesIt provides the protection to the original object from the outside world.

References!1. http://www.javatpoint.com

2. https://www.tutorialspoint.com/design_pattern

3. http://www.oodesign.com

4. https://sourcemaking.com/design_patterns

5. https://www.youtube.com/playlist?list=PLF206E906175C7E07

Thank You !

Presented By : Michael Adel @ Perceptive Mind .