50
Introduction to Design Patterns M.B.Chandak [email protected]

Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

  • Upload
    lyminh

  • View
    232

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Introduction to Design PatternsM.B.Chandak

[email protected]

Page 2: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Agenda• Basics of OOP and relationship with Design Patterns• Implementation of basics in Netbeans

• Abstraction• Inheritance• Encapsulation

• Introduction to Design Patterns• Elements of Pattern• Classification of Design Patterns• Characteristics of Design Patterns

Page 3: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Basic concepts of OOPS• Object Oriented Programming: Four Basic pillars• Abstraction• Polymorphism• Inheritance• Encapsulation

Page 4: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Abstraction• Focus on Essential characteristics• Ignore the irrelevant• Ignore the unimportant• For example: Table No specifications are required at the time of

definitions: i.e., size, shape, color etc.• It is considered as IDEA and not materialization• Example: Bank Account• There can several types of bank accounts like, saving, current,

industrial, demat etc..• But the main requirement at abstraction level is account number and

balance.

Page 5: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Inheritance: Reusability• One class attribute, behavior are passed to another class (Parent –

Child relationship)• Superclass – Subclass relationship.• There can be more than one Superclass, but it generates sometimes

not allowed in JAVA.• Inheritance permits polymorphism.

Page 6: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Encapsulation : Protection• Auditing and logging• Data is accessible through the methods presents in the class• Black boxing• Referring contacts using “contacts” or “logs”• It reduces dependencies, i.e., change at one place will not affect the

other places.• How much to be protected: JAVA rule: As much as possible

Page 7: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Encapsulation : Protection• Many forms, complex and very powerful.• Example “overloading operator”• Has in-built intelligence / but written by coder.• Flexibility and selection correct option w.r.t. time.• One of the important concept is “Overriding”.• Class A: Bank account, has a “withdraw” method.• Class B: Inherits Class A and if in class B, the method “withdraw” is

present, then there will be two occurrence of “withdraw”.• Which method to use when: Overriding• Same method name, same set of arguments with same return type:

Overriding.

Page 8: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Encapsulation : Protection• Overriding is different than Overloading.• Overriding is vertical in nature. Function which are completely same

but are at different level of inheritance.• Overloading is horizontal.• Same level of code, with different arguments and return type.

Page 9: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Design Pattern: Definition“Each pattern describes a problem which occurs over and over again

in our environment, and then describes the core of the solution tothat problem, in such a way that you can use this solution a milliontimes over, without ever doing it the same way twice.” [1]

[Christopher Alexander]

Design patterns capture the best practices of experienced object-oriented software developers.

Design patterns are solutions to general software developmentproblems.

Page 10: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Design Pattern: Downside• Are based on the principles of object-oriented programming:

abstraction, inheritance, polymorphism and association.• Are solutions to recurring problems to software design.• Are independent of the application domain.• Example – Variability of interfaces – the model view controller (MVC)

pattern• Although design patterns are useful in promoting flexibility, this

maybe at the expense of a more complicated design.• There does not exist

• A standardization for indexing patterns• General practices/processes for using design patterns during the design

process have not as yet been established

Page 11: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Elements of Design PatternIn general, a pattern has four essential elements.

The pattern name The problem The solution The consequences

Page 12: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Description: Pattern NameThe pattern name is a handle we can use to describe a design problem,

its solutions, and consequences in a word or two.

Naming a pattern immediately increases the design vocabulary. It lets usdesign at a higher level of abstraction. Having a vocabulary for patterns lets us talk about them. It makes it easier to think about designs and to communicate them and their

trade-offs to others.

Page 13: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Description: ProblemThe problem describes when to apply the pattern.

It explains the problem and its context. It might describe specific design problems such as how to represent

algorithms as objects. It might describe class or object structures that are symptomatic of an

inflexible design. Sometimes the problem will include a list of conditions that must be met

before it makes sense to apply the pattern.

Page 14: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Description: SolutionThe solution describes the elements that make up the design, their

relationships, responsibilities, and collaborations.

The solution doesn't describe a particular concrete design or implementation,because a pattern is like a template that can be applied in many differentsituations. Instead, the pattern provides an abstract description of a design problem and

how a general arrangement of elements (classes and objects in our case)solves it.

Page 15: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Description: ConsequencesThe consequences are the results and trade-offs of applying the

pattern.

The consequences for software often concern space and time trade-offs. They may address language and implementation issues as well. Since reuse is often a factor in object-oriented design, the consequences of a

pattern include its impact on a system's flexibility, extensibility, or portability. Listing these consequences explicitly helps you understand and evaluate them

Page 16: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Basic types of Design PatternsGang of 4: Defined three basic types of Design patterns Creational patterns are ones that create objects for you, rather than having

you instantiate objects directly. This gives your program more flexibility indeciding which objects need to be created for a given case.

Structural patterns help you compose groups of objects into larger structures,such as complex user interfaces or accounting data.

Behavioral patterns help you define the communication between objects inyour system and how the flow is controlled in a complex program

Page 17: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Creational Patterns

Page 18: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Creational PatternThese design patterns provides way to create objects while hiding the

creation logic, rather than instantiating objects directly using newoperator. This gives program more flexibility in deciding which objectsneed to be created for a given use case.

In many cases, the exact nature of the object that is created could varywith the needs of the program and abstracting the creation processinto a special “creator” class can make your program more flexibleand general

Page 19: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Creational Pattern: Classification The Factory Pattern provides a simple decision making class that

returns one of several possible subclasses of an abstract base classdepending on the data that are provided. The Abstract Factory Pattern provides an interface to create and

return one of several families of related objects. The Builder Pattern separates the construction of a complex object

from its representation. The Prototype Pattern starts with an initialized and instantiated class

and copies or clones it to make new instances rather than creatingnew instances. The Singleton Pattern is a class of which there can be no more than

one instance. It provides a single global point of access to thatinstance.

Page 20: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Factory Pattern

Page 21: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Working:

Here, x is a base class and classes xy and xz are derived from it.

The Factory is a class that decides which of these subclasses to return dependingon the arguments you give it.

The getClass() method passes in some value abc, and returns some instance ofthe class x. Which one it returns doesn't matter to the programmer since they allhave the same methods, but different implementations.

Page 22: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

When to use Factory patternYou should consider using a Factory pattern when: A class can’t anticipate which kind of class of objects it must create. A class uses its subclasses to specify which objects it creates. You want to localize the knowledge of which class gets created.

There are several similar variations on the factory pattern to recognize: The base class is abstract and the pattern must return a complete working

class. The base class contains default methods and is only subclass for cases

where the default methods are insufficient. Parameters are passed to the factory telling it which of several class types

to return. In this case the classes may share the same method names butmay do something quite different.

Page 23: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Abstract Factory Pattern• Provide an interface for creating families of related or dependent

objects without specifying their concrete classes.• Also Known As

• KitExample:• Consider a user interface toolkit that supports multiple look-and-feel

standards. Different look-and-feels defines different appearances andbehaviors for user interface.

• An application should not hard-code its widgets for a particular look-and-feel.

• Instantiating look-and-feel-specific classes of widgets throughout theapplication makes it hard to change the look and feel later

Page 24: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Abstract Factory Pattern• We can solve this problem by defining an abstract WidgetFactory

class that declares an interface for creating each basic kind of widget.• There is also an abstract class for each kind of widget, and concrete

subclasses implement widgets for specific look-and-feel standards.• Use the Abstract Factory pattern when

• a system should be independent of how its products are created, composed,and represented.

• a system should be configured with one of multiple families of products.• a family of related product objects is designed to be used together, and you

need to enforce this constraint.• You want to provide a class library of products, and you want to reval just

their interfaces, not their implementations

Page 25: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Singleton Design Pattern• Used when the class have only one single instance.• The instance is globally accessible.• Rules

• Create a Class• Create a private default constructor• Create a private static variable to generate the object of

class• Create an accessor

Page 26: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Singleton Design Pattern

Page 27: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Applications• Logger Class• Configuration class• Accessing resources in shared mode

Page 28: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Builder and Prototype Pattern• Builder pattern builds a complex object using simple objects and

using a step by step approach. This type of design pattern comesunder creational pattern as this pattern provides one of the best waysto create an object.

• A Builder class builds the final object step by step. This builder isindependent of other objects.

• Prototype pattern refers to creating duplicate object while keepingperformance in mind. This type of design pattern comes undercreational pattern as this pattern provides one of the best way tocreate an object.

Page 29: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Structural Patterns

Page 30: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Structural Patterns Structural patterns describe how classes and objects can be combined

to form larger structures. The difference between class patterns and object patterns is that

class patterns describe how inheritance can be used to provide moreuseful program interfaces. Object patterns, on the other hand, describe how objects can be

composed into larger structures using object composition, or theinclusion of objects within other objects.

Page 31: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Types of Structural Design PatternsAdapterCompositeProxyFlyweightFaçadeBridgeDecorator

Page 32: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Description The Adapter pattern can be used to make one class interface match

another to make programming easier.

The Composite pattern is a composition of objects, each of which maybe either simple or itself a composite object.

The Proxy pattern is frequently a simple object that takes the place ofa more complex object that may be invoked later, for example whenthe program runs in a network environment.

Page 33: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Description The Flyweight pattern is a pattern for sharing objects, where each instance does

not contain its own state, but stores it externally. This allows efficient sharing ofobjects to save space, when there are many instances, but only a few differenttypes.

Intrinsic state: Constant Extrinsic state: On the fly

The Façade pattern is used to make a single class represent an entire subsystem.

The Bridge pattern separates an object’s interface from its implementation, soyou can vary them separately.

The Decorator pattern, which can be used to add responsibilities to objectsdynamically.

Page 34: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Adapter Pattern Object adapters use a compositional technique to adapt one interface

to another. The adapter inherits the target interface that the client expects to

see, while it holds an instance of the adaptee. When the client calls the request() method on its target object (the

adapter), the request is translated into the corresponding specificrequest on the adaptee. Object adapters enable the client and the adaptee to be completely

decoupled from each other. Only the adapter knows about both ofthem.

Page 35: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Adapter: Example

Page 36: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Composite DP• This pattern design the Tree structure of any process.• Dividing the process components into different nodes of tree is main

task of CDP.• Each node in the tree has defined task.• Tree represents group of object.• Dependencies between objects and relationship between objects is

important.• Very useful DP to handle Database applications (using non-linear

trees)• Object grouping: Example: collection of services to run the product.

Page 37: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Flyweight DP• Commonly used in Game design.• Basic objective to create actors.• Memory management play important role.• VM wares can be used to improve the speed.• Example:• Creating 50 enemies at some level of game and 100 enemies at

higher level.• The cache will have single enemy structure and FDP will create the

multiple structures based on level.• For example: Color of background and creating enemies.

Page 38: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Façade DP• Provide a unified interface at memory level.• Easier subsystem to generate a complex system.• It is collection of subsystems and subsystem interact with main class

using message passing technique.• Handing messages and queuing mechanism play important role.• For example:• Information Desk about the Big mall.• Help Desk• Travel Desk in hotels.• Big-Bazar inventory control system.

Page 39: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Decorator DP• The DP will add new functionality to an existing object without

altering its structure.• It is capable of dynamically changing the functionality of object at

run-time.• Commonly used with Factory pattern.• For example:• Decorating the object.• Mobile application with decorating features.

Page 40: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Behavioral Patterns

Page 41: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Introduction• Identifies common communication patters between objects and

realize these patterns.• Increase flexibility of communication between objects• Interaction between objects which are loosely coupled in n-tier

architecture.• Explains about how objects interacts and make things happen

Page 42: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Types of Behavioral Patterns

•Iterator•Observer•Chain of responsibility•Memento•Template Design pattern•Mediator Design pattern

Page 43: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Iterator Design pattern• Access the elements of collect objects in sequential manner• Collection object is a container [array/linked list/set]• The access is without knowing any underlying representation.• Access the elements of container: For example of element of array in

sequential manner.

Page 44: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Observer Design Pattern• Object called the subject maintain the list of its dependents, called as

observer and notify them automatically of any state change, usuallyby calling one of their methods.

• One-to-many relationship between objects.• When one object changes the state all its dependent objects are

notified.• It is also called as listener.• Two components: Subject and Listener

Page 45: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Example of Observer design pattern• Subject: Flipkart service provider• Observers: Registered users on Flipkart.• Interaction: Notification.• For example: if observers are interested in buying certain items on

Flipkart, and the item is not available.• Once the item is available at Flipkart, the service provider will inform

all the registered user via email.• Designing notification application on mobiles is common example of

Observer pattern.• Sending bulk SMS

Page 46: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Chain of Responsibility DP• Basic: The receiver of message is responsible for serving the message.• Two COR models: Single receiver and Chained receiver• For example: Quiz and ATM• The Agent logic to decide the particular receiver will play vital role.• In single receiver model: if one receiver is not able to provide the

service, message is passed to another receiver.• In Chained receiver model: the receiver will have the ability to decide

whether it is possible to satisfy the request.

Page 47: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Memento DP• Commonly used when it is required to hold the state of process and

perform redo, undo, rollback operations.• Very useful pattern for Database application.• For example:• UNDO operation of MS-WORD.• Context saving of process and starting the process from the same

state.• Rollback and Savepoint operations in databases.

Page 48: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Template DP• This pattern is used for performing similar types of

operations/processes for different types of devices.• For example: Designing device drivers for different printers.• The template includes: basic ideas of process to be performed.• For example:• Writing device driver for Hp and Epson printer. The input and output

model remains same, but the interface model changes.• Writing a manufacturing process for car: Car skeleton, Car Engine, Car

door etc can be component of template and based upon the type ofcar the component behavior changes.

Page 49: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

Mediator DP• This pattern is used for creating platform for sharing.• One of the common application of MDP is social media.• For example: Facebook• If user-A needs to share a link with different users, then it can use

Facebook main platform and all friends of user – A will be able to getinformation about the link.

• The DP needs message passing mechanism.• Use of Friend – Function will allow to categories the shared and

restricted components.

Page 50: Introduction to Design Patterns - mbchandak.com · • Basics of OOP and relationship with Design Patterns • Implementation of basics in Netbeans • Abstraction • Inheritance

It is collection of study material available on various web-sites and will help students tounderstand the basics of Design Patterns.

Thank You