SlideShare a Scribd company logo
1 of 32
DESIGN PATTERNS
         S.SRIKRISHNAN
           FINAL YEAR
DEPARTMENT OF COMPUTER SCIENCE
  SSN COLLEGE OF ENGINEERING
Overview
•   Introduction
•   Software Architecture
•   Issues in Software Development
•   GoF patterns
•   Basic Class relationships
•   Design Principles – 1,2,3
•   Design Principles to Design Patterns
•   Observer Pattern
Introduction
• “Programming is fun, but developing quality
  software is hard” – Craig Larman
• The focus is on OO software development
• Built using OO Framework – Java, .NET,
  Python, C++, Smalltalk etc.
• “Owning a hammer doesn’t make one an
  architect”
• Many issues during development have to be
  resolved
Software Architecture
A dog house   A multi storey building
Differences
•   Scale
•   Process
•   Cost
•   Schedule
•   Skills and development teams
•   Materials and technologies
•   Stakeholders
•   Risks
It’s an engineering task
Software Engineer   Civil Engineer
Issues in Software Development
• Unclear requirements
• Continuously changing requirements
• Miscommunications
• How to design the software classes – Huh ! Looks
  like the most difficult problem
• How to assign responsibilities to classes – What
  classes should do what?
• All these imply something - The code being
  developed should be reusable, highly cohesive
  and less coupled
Design Patterns come to our rescue
• They are elements of reusable Object Oriented
  Software
• Try to exploit the wisdom and lessons learnt by the
  OO developers who faced similar design problems
• An object-oriented system's quality can be judged
  looking at the manner in which patterns have been
  used
• Several design patterns have been suggested by the
  GoF (Gang of Four)
GoF – Who are they ?
• Erich Gamma, Richard
  Helm, Ralph Johnson, John
  Vlissides (Gang of Four)
• They published a book
  “Design Pattens by GoF” in
  1994 which was a major
  milestone       in       OO
  development
• This book is considered the
  “bible” for Design Patterns
• It describes 23 patterns for
  good OO design
“One man’s pattern is another
man’s primitive building block”
Basic Class Relationships
•   Generalization (Is – a)
•   Realization (Implements – a)
•   Association (Has – a / uses)
•   Composition (Is composed of)
Design Principles
• “Identify the aspects of your application that
  vary and separate them from what stays the
  same”
• “Program to an interface, not an
  implementation”
• “Favor composition over inheritance”
Design Principle – 1
• “Identify the aspects of your application that
  vary and separate them from what stays the
  same”
• Take the parts that vary and encapsulate them
• You can later alter or extend the parts that vary
  without affecting those that don’t
• Let’s see how to apply this for a Duck class
Designing a Duck class
• A duck may fly, quack – depends on the type of duck
  (sub classes of Duck)
• So, can we put quack and fly methods in Duck class?
   – A problem, because all types may not quack or fly
• So, can we have these methods in duck class, and
  override them in sub classes, so that ducks that should
  not fly or quack will override to do nothing?
   – A bigger problem, because, it is unstable to
     changes
Designing a Duck class
• So, what about an interface?
• Lets define an interface Flyable with fly
  method and Quackable with Quack method
• All sub ducks extend Duck class and
  implement the necessary interface(s)
• Does that solve this problem really?
  – No, it shows no improvement
  – Code is still not reusable
Designing a Duck class
• So here lies the problem : Quack and fly
  methods have to be implemented in all the sub
  classes.
• If there is a need to change the flying or
  quacking style, we need to go to all classes and
  modify them
• Let’s try to find a solution to this : Apply the
  previously mentioned principle
Applying the design principle
• Pull out what varies : Quack and Fly behaviour
• Allocate separate interfaces FlyBehaviour and
  QuackBehaviour
• Write 2 classes FlyWithWings and FlyNoWay
  that implements FlyBehaviour
• Write 2 more classes Quack and MuteQuack
  that implements QuackBehaviour
Applying the design principle
• Override fly method in FlyWithWings with
  necessary implementation and in FlyNoWay
  without any implementation
• Override quack method in Quack with
  necessary implementation and in NoQuack
  without any implementation
• Create an association with the Duck class and
  the two encapsulated Behaviour classes :
  FlyBehaviour and QuackBehaviour
Design Principle – 2
• “Program to an interface, not an
  implementation”
• Programming to an interface means
  programming to a super type
• This helps in exploiting polymorphism : the
  actual runtime object isn’t locked into the code
• Objects assigned can be any concrete
  implementation of the super type
Design Principle – 3
•   “Favor composition over inheritance”
•   It adds flexibility to the code
•   It helps encapsulate family of algorithms
•   It helps us change behavior at runtime
•   As seen in the above example, composition
    yields better design than inheritance
From principles to patterns
• All patterns that have been framed adopt the 3
  basic design principles
• When you use a pattern in a description, other
  developers quickly know precisely the design
  you have in your mind
• A team well versed in design patterns can
  move forward more quickly with less room for
  misunderstanding
Observer Pattern
•   Most widely used patterns in the JDK
•   Publisher – Subscriber Pattern
•   Event Delegation Model
•   Different kinds of subscriber objects are
    interested in the state change or events of a
    publisher object, and want to react in their own
    unique way when the publisher generates an
    event.
Observer Pattern
• Define a subscriber or listener interface
• Subscribers implement this interface
• The publisher can dynamically register
  subscribers who are interested in an event and
  notify them when an even occurs.
• We could implement the Observer pattern
  “from scratch” in Java
• Java provides the Observable/Observer classes
  as built-in support for the Observer pattern
Observer Pattern
• The java.util.Observable class is the base Subject
  class. Any Class that wants to be observed
  extends this class
  – Provides methods to add/delete observers
  – Provides methods to notify all observers
  – A subclass only needs to ensure that its observers are
    notified in the appropriate mutators
  – Uses a Vector for storing the observer references
• The java.util.Observer interface is the Observer
  interface.   It must be implemented by any
  observer class
Observer Pattern
/**
 * A subject to observe!
 */
public class ConcreteSubject extends Observable {
 private String name;
 private float price;
 public ConcreteSubject(String name, float price) {
   this.name = name;
   this.price = price;
   System.out.println("ConcreteSubject created: " + name + "
    at "
     + price);
 }
Observer Pattern
public String getName() {return name;}
  public float getPrice() {return price;}
  public void setName(String name) {
    this.name = name;
    setChanged();
    notifyObservers(name);
  }
  public void setPrice(float price) {
    this.price = price;
    setChanged();
    notifyObservers(new Float(price));
  }
}
Observer Pattern
// An observer of name changes.
public class NameObserver implements Observer {
  private String name;
  public NameObserver() {
    name = null;
    System.out.println("NameObserver created: Name is " + name);
  }
  public void update(Observable obj, Object arg) {
    if (arg instanceof String) {
      name = (String)arg;
      System.out.println("NameObserver: Name changed to " + name);
    } else {
      System.out.println("NameObserver: Some other change to
subject!");
    }
  }
Observer Pattern
// An observer of price changes.
public class PriceObserver implements Observer {
  private float price;
  public PriceObserver() {
    price = 0;
    System.out.println("PriceObserver created: Price is " + price);
  }
  public void update(Observable obj, Object arg) {
    if (arg instanceof Float) {
      price = ((Float)arg).floatValue();
      System.out.println("PriceObserver: Price changed to " +
                   price);
    } else {
      System.out.println(”PriceObserver: Some other change to
    subject!");
    }}
Observer Pattern
// Test program for ConcreteSubject, NameObserver and PriceObserver
public class TestObservers {
  public static void main(String args[]) {
    // Create the Subject and Observers.
    ConcreteSubject s = new ConcreteSubject("Corn Pops", 1.29f);
    NameObserver nameObs = new NameObserver();
    PriceObserver priceObs = new PriceObserver();
    // Add those Observers!
    s.addObserver(nameObs);
    s.addObserver(priceObs);
    // Make changes to the Subject.
    s.setName("Frosted Flakes");
    s.setPrice(4.57f);
    s.setPrice(9.22f);
    s.setName("Sugar Crispies");
  }
}
Observer Pattern
• Test program output
ConcreteSubject created: Corn Pops at 1.29
NameObserver created: Name is null
PriceObserver created: Price is 0.0
PriceObserver: Some other change to subject!
NameObserver: Name changed to Frosted Flakes
PriceObserver: Price changed to 4.57
NameObserver: Some other change to subject!
PriceObserver: Price changed to 9.22
NameObserver: Some other change to subject!
PriceObserver: Some other change to subject!
NameObserver: Name changed to Sugar Crispies
Many more Pattern
•   Decorator Pattern
•   Factory Pattern
•   Singleton Pattern
•   Command Pattern
•   Template Method Pattern
•   Adapter Pattern
•   State Pattern
•   Proxy Pattern etc.
Thank You !

More Related Content

Viewers also liked

Design patterns
Design patternsDesign patterns
Design patternsISsoft
 
Design Pattern - 2. Observer
Design Pattern -  2. ObserverDesign Pattern -  2. Observer
Design Pattern - 2. ObserverFrancesco Ierna
 
The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)John Ortiz
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton patternbabak danyal
 
Design patterns: observer pattern
Design patterns: observer patternDesign patterns: observer pattern
Design patterns: observer patternJyaasa Technologies
 
Observer Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 AugObserver Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 Augmelbournepatterns
 
Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - observer patternpixelblend
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa TouchEliah Nikans
 
Reflective portfolio
Reflective portfolioReflective portfolio
Reflective portfoliojobbo1
 
Design Pattern - Observer Pattern
Design Pattern - Observer PatternDesign Pattern - Observer Pattern
Design Pattern - Observer PatternMudasir Qazi
 
Observer design pattern
Observer design patternObserver design pattern
Observer design patternSara Torkey
 
Observer Pattern
Observer PatternObserver Pattern
Observer PatternAkshat Vig
 
Observer design pattern
Observer design patternObserver design pattern
Observer design patternSameer Rathoud
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software EngineeringNadimozzaman Pappo
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator PatternJonathan Simon
 

Viewers also liked (20)

Design patterns
Design patternsDesign patterns
Design patterns
 
Design Pattern - 2. Observer
Design Pattern -  2. ObserverDesign Pattern -  2. Observer
Design Pattern - 2. Observer
 
The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)The Observer Pattern (Definition using UML)
The Observer Pattern (Definition using UML)
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Design patterns: observer pattern
Design patterns: observer patternDesign patterns: observer pattern
Design patterns: observer pattern
 
Observer Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 AugObserver Pattern Khali Young 2006 Aug
Observer Pattern Khali Young 2006 Aug
 
Design patterns 4 - observer pattern
Design patterns   4 - observer patternDesign patterns   4 - observer pattern
Design patterns 4 - observer pattern
 
Factory Pattern
Factory PatternFactory Pattern
Factory Pattern
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
 
Reflective portfolio
Reflective portfolioReflective portfolio
Reflective portfolio
 
Design patterns - Observer Pattern
Design patterns - Observer PatternDesign patterns - Observer Pattern
Design patterns - Observer Pattern
 
Design Pattern - Observer Pattern
Design Pattern - Observer PatternDesign Pattern - Observer Pattern
Design Pattern - Observer Pattern
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Observer Pattern
Observer PatternObserver Pattern
Observer Pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Observer design pattern
Observer design patternObserver design pattern
Observer design pattern
 
Design pattern - Software Engineering
Design pattern - Software EngineeringDesign pattern - Software Engineering
Design pattern - Software Engineering
 
Observer and Decorator Pattern
Observer and Decorator PatternObserver and Decorator Pattern
Observer and Decorator Pattern
 

Similar to Design Patterns and Principles Explained

Mcknight well built extensions
Mcknight well built extensionsMcknight well built extensions
Mcknight well built extensionsRichard McKnight
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptSanthosh Kumar Srinivasan
 
New types of tests for Java projects
New types of tests for Java projectsNew types of tests for Java projects
New types of tests for Java projectsVincent Massol
 
Advanced Java Testing @ POSS 2019
Advanced Java Testing @ POSS 2019Advanced Java Testing @ POSS 2019
Advanced Java Testing @ POSS 2019Vincent Massol
 
The maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesThe maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesMuhammad Raza
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
The programming philosophy of jrql
The programming philosophy of jrqlThe programming philosophy of jrql
The programming philosophy of jrqlmsg systems ag
 
Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLIDPranalee Rokde
 
DSL's with Groovy
DSL's with GroovyDSL's with Groovy
DSL's with Groovypaulbowler
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
The art of architecture
The art of architectureThe art of architecture
The art of architectureADDQ
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptRushikeshChikane1
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptRushikeshChikane2
 
Lesson12 other behavioural patterns
Lesson12 other behavioural patternsLesson12 other behavioural patterns
Lesson12 other behavioural patternsOktJona
 

Similar to Design Patterns and Principles Explained (20)

Mcknight well built extensions
Mcknight well built extensionsMcknight well built extensions
Mcknight well built extensions
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
Design Patterns.ppt
Design Patterns.pptDesign Patterns.ppt
Design Patterns.ppt
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
New types of tests for Java projects
New types of tests for Java projectsNew types of tests for Java projects
New types of tests for Java projects
 
L05 Design Patterns
L05 Design PatternsL05 Design Patterns
L05 Design Patterns
 
Design Patterns - GOF
Design Patterns - GOFDesign Patterns - GOF
Design Patterns - GOF
 
Advanced Java Testing @ POSS 2019
Advanced Java Testing @ POSS 2019Advanced Java Testing @ POSS 2019
Advanced Java Testing @ POSS 2019
 
The maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID PrinciplesThe maze of Design Patterns & SOLID Principles
The maze of Design Patterns & SOLID Principles
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
L03 Design Patterns
L03 Design PatternsL03 Design Patterns
L03 Design Patterns
 
Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
 
The programming philosophy of jrql
The programming philosophy of jrqlThe programming philosophy of jrql
The programming philosophy of jrql
 
Design principles - SOLID
Design principles - SOLIDDesign principles - SOLID
Design principles - SOLID
 
DSL's with Groovy
DSL's with GroovyDSL's with Groovy
DSL's with Groovy
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
The art of architecture
The art of architectureThe art of architecture
The art of architecture
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.ppt
 
Chapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.pptChapter 4_Introduction to Patterns.ppt
Chapter 4_Introduction to Patterns.ppt
 
Lesson12 other behavioural patterns
Lesson12 other behavioural patternsLesson12 other behavioural patterns
Lesson12 other behavioural patterns
 

More from Srikrishnan Suresh (10)

Sources of Innovation
Sources of InnovationSources of Innovation
Sources of Innovation
 
Second review presentation
Second review presentationSecond review presentation
Second review presentation
 
First review presentation
First review presentationFirst review presentation
First review presentation
 
Final presentation
Final presentationFinal presentation
Final presentation
 
Zeroth review presentation
Zeroth review presentationZeroth review presentation
Zeroth review presentation
 
All pairs shortest path algorithm
All pairs shortest path algorithmAll pairs shortest path algorithm
All pairs shortest path algorithm
 
Canvas based presentation
Canvas based presentationCanvas based presentation
Canvas based presentation
 
ANSI C Macros
ANSI C MacrosANSI C Macros
ANSI C Macros
 
Merge sort
Merge sortMerge sort
Merge sort
 
Theory of LaTeX
Theory of LaTeXTheory of LaTeX
Theory of LaTeX
 

Recently uploaded

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 

Recently uploaded (20)

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 

Design Patterns and Principles Explained

  • 1. DESIGN PATTERNS S.SRIKRISHNAN FINAL YEAR DEPARTMENT OF COMPUTER SCIENCE SSN COLLEGE OF ENGINEERING
  • 2. Overview • Introduction • Software Architecture • Issues in Software Development • GoF patterns • Basic Class relationships • Design Principles – 1,2,3 • Design Principles to Design Patterns • Observer Pattern
  • 3. Introduction • “Programming is fun, but developing quality software is hard” – Craig Larman • The focus is on OO software development • Built using OO Framework – Java, .NET, Python, C++, Smalltalk etc. • “Owning a hammer doesn’t make one an architect” • Many issues during development have to be resolved
  • 4. Software Architecture A dog house A multi storey building
  • 5. Differences • Scale • Process • Cost • Schedule • Skills and development teams • Materials and technologies • Stakeholders • Risks
  • 6. It’s an engineering task Software Engineer Civil Engineer
  • 7. Issues in Software Development • Unclear requirements • Continuously changing requirements • Miscommunications • How to design the software classes – Huh ! Looks like the most difficult problem • How to assign responsibilities to classes – What classes should do what? • All these imply something - The code being developed should be reusable, highly cohesive and less coupled
  • 8. Design Patterns come to our rescue • They are elements of reusable Object Oriented Software • Try to exploit the wisdom and lessons learnt by the OO developers who faced similar design problems • An object-oriented system's quality can be judged looking at the manner in which patterns have been used • Several design patterns have been suggested by the GoF (Gang of Four)
  • 9. GoF – Who are they ? • Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (Gang of Four) • They published a book “Design Pattens by GoF” in 1994 which was a major milestone in OO development • This book is considered the “bible” for Design Patterns • It describes 23 patterns for good OO design
  • 10. “One man’s pattern is another man’s primitive building block”
  • 11. Basic Class Relationships • Generalization (Is – a) • Realization (Implements – a) • Association (Has – a / uses) • Composition (Is composed of)
  • 12. Design Principles • “Identify the aspects of your application that vary and separate them from what stays the same” • “Program to an interface, not an implementation” • “Favor composition over inheritance”
  • 13. Design Principle – 1 • “Identify the aspects of your application that vary and separate them from what stays the same” • Take the parts that vary and encapsulate them • You can later alter or extend the parts that vary without affecting those that don’t • Let’s see how to apply this for a Duck class
  • 14. Designing a Duck class • A duck may fly, quack – depends on the type of duck (sub classes of Duck) • So, can we put quack and fly methods in Duck class? – A problem, because all types may not quack or fly • So, can we have these methods in duck class, and override them in sub classes, so that ducks that should not fly or quack will override to do nothing? – A bigger problem, because, it is unstable to changes
  • 15. Designing a Duck class • So, what about an interface? • Lets define an interface Flyable with fly method and Quackable with Quack method • All sub ducks extend Duck class and implement the necessary interface(s) • Does that solve this problem really? – No, it shows no improvement – Code is still not reusable
  • 16. Designing a Duck class • So here lies the problem : Quack and fly methods have to be implemented in all the sub classes. • If there is a need to change the flying or quacking style, we need to go to all classes and modify them • Let’s try to find a solution to this : Apply the previously mentioned principle
  • 17. Applying the design principle • Pull out what varies : Quack and Fly behaviour • Allocate separate interfaces FlyBehaviour and QuackBehaviour • Write 2 classes FlyWithWings and FlyNoWay that implements FlyBehaviour • Write 2 more classes Quack and MuteQuack that implements QuackBehaviour
  • 18. Applying the design principle • Override fly method in FlyWithWings with necessary implementation and in FlyNoWay without any implementation • Override quack method in Quack with necessary implementation and in NoQuack without any implementation • Create an association with the Duck class and the two encapsulated Behaviour classes : FlyBehaviour and QuackBehaviour
  • 19. Design Principle – 2 • “Program to an interface, not an implementation” • Programming to an interface means programming to a super type • This helps in exploiting polymorphism : the actual runtime object isn’t locked into the code • Objects assigned can be any concrete implementation of the super type
  • 20. Design Principle – 3 • “Favor composition over inheritance” • It adds flexibility to the code • It helps encapsulate family of algorithms • It helps us change behavior at runtime • As seen in the above example, composition yields better design than inheritance
  • 21. From principles to patterns • All patterns that have been framed adopt the 3 basic design principles • When you use a pattern in a description, other developers quickly know precisely the design you have in your mind • A team well versed in design patterns can move forward more quickly with less room for misunderstanding
  • 22. Observer Pattern • Most widely used patterns in the JDK • Publisher – Subscriber Pattern • Event Delegation Model • Different kinds of subscriber objects are interested in the state change or events of a publisher object, and want to react in their own unique way when the publisher generates an event.
  • 23. Observer Pattern • Define a subscriber or listener interface • Subscribers implement this interface • The publisher can dynamically register subscribers who are interested in an event and notify them when an even occurs. • We could implement the Observer pattern “from scratch” in Java • Java provides the Observable/Observer classes as built-in support for the Observer pattern
  • 24. Observer Pattern • The java.util.Observable class is the base Subject class. Any Class that wants to be observed extends this class – Provides methods to add/delete observers – Provides methods to notify all observers – A subclass only needs to ensure that its observers are notified in the appropriate mutators – Uses a Vector for storing the observer references • The java.util.Observer interface is the Observer interface. It must be implemented by any observer class
  • 25. Observer Pattern /** * A subject to observe! */ public class ConcreteSubject extends Observable { private String name; private float price; public ConcreteSubject(String name, float price) { this.name = name; this.price = price; System.out.println("ConcreteSubject created: " + name + " at " + price); }
  • 26. Observer Pattern public String getName() {return name;} public float getPrice() {return price;} public void setName(String name) { this.name = name; setChanged(); notifyObservers(name); } public void setPrice(float price) { this.price = price; setChanged(); notifyObservers(new Float(price)); } }
  • 27. Observer Pattern // An observer of name changes. public class NameObserver implements Observer { private String name; public NameObserver() { name = null; System.out.println("NameObserver created: Name is " + name); } public void update(Observable obj, Object arg) { if (arg instanceof String) { name = (String)arg; System.out.println("NameObserver: Name changed to " + name); } else { System.out.println("NameObserver: Some other change to subject!"); } }
  • 28. Observer Pattern // An observer of price changes. public class PriceObserver implements Observer { private float price; public PriceObserver() { price = 0; System.out.println("PriceObserver created: Price is " + price); } public void update(Observable obj, Object arg) { if (arg instanceof Float) { price = ((Float)arg).floatValue(); System.out.println("PriceObserver: Price changed to " + price); } else { System.out.println(”PriceObserver: Some other change to subject!"); }}
  • 29. Observer Pattern // Test program for ConcreteSubject, NameObserver and PriceObserver public class TestObservers { public static void main(String args[]) { // Create the Subject and Observers. ConcreteSubject s = new ConcreteSubject("Corn Pops", 1.29f); NameObserver nameObs = new NameObserver(); PriceObserver priceObs = new PriceObserver(); // Add those Observers! s.addObserver(nameObs); s.addObserver(priceObs); // Make changes to the Subject. s.setName("Frosted Flakes"); s.setPrice(4.57f); s.setPrice(9.22f); s.setName("Sugar Crispies"); } }
  • 30. Observer Pattern • Test program output ConcreteSubject created: Corn Pops at 1.29 NameObserver created: Name is null PriceObserver created: Price is 0.0 PriceObserver: Some other change to subject! NameObserver: Name changed to Frosted Flakes PriceObserver: Price changed to 4.57 NameObserver: Some other change to subject! PriceObserver: Price changed to 9.22 NameObserver: Some other change to subject! PriceObserver: Some other change to subject! NameObserver: Name changed to Sugar Crispies
  • 31. Many more Pattern • Decorator Pattern • Factory Pattern • Singleton Pattern • Command Pattern • Template Method Pattern • Adapter Pattern • State Pattern • Proxy Pattern etc.