SlideShare una empresa de Scribd logo
1 de 52
Descargar para leer sin conexión
DESIGN PATTERNS
       hugo sereno ferreira . joão pascoal faria . jorge barbosa . nuno flores




A L IG H TW E I G H T INTROD UC TION
ARCHITECTURE




 ... a cabana seems simple ...
ARCHITECTURE




 ... easier than an house ...
ARCHITECTURE




... child’s play next to a building ...
ARCHITECTURE




... but nothing compared to a city!
WHERE’S THE DIFFERENCES?

• Size.   From a small cabana, to a large city.
• Cost.     From less than €1k, to more than €1.000.000k
• Time. Taking    a day, to evolving through centuries.
• Process.    Doing as an hobby v.s. planning.
• Skills.   From a layman, to highly qualified professionals.
• Risk. Vacations    v.s. a population of millions.
• ...
FINDING THE BEST DESIGN
             time

                             –
         –          +
                                      scope

                        –
  cost                            –
                +
                            quality
DEFINITION


“   Architecture is the process and product of planning,
    designing and constructing physical form, space and
    ambience that reflect functional, technical, social, and
    aesthetic considerations.


                                                    Wikipedia
SOFTWARE?


“   ... the process and product of planning, designing and
    constructing logical form, space and ambience that
    reflect functional, technical, social, and aesthetic
    considerations.
QUALITY IN SOFTWARE
✦   accessibility          ✦   configurability     ✦   integrity            ✦   relevance         ✦   survivability
✦   accountability         ✦   correctness        ✦   interchangeability   ✦   reliability       ✦   sustainability
✦   accuracy               ✦   customizability    ✦   interoperability     ✦   repeatability     ✦   tailorability
✦   adaptability           ✦   degradability      ✦   learnability         ✦   reproducibility   ✦   testability
✦   administrability       ✦   demonstrability    ✦   maintainability      ✦   responsiveness    ✦   timeliness
✦   affordability          ✦   dependability      ✦   manageability        ✦   reusability       ✦   understandability
✦   agility                ✦   deployability      ✦   mobility             ✦   robustness        ✦   usability
✦   auditability           ✦   distributability   ✦   modularity           ✦   safety            ✦   ...
✦   availability           ✦   durability         ✦   nomadicity           ✦   scalability
✦   credibility            ✦   evolvability       ✦   operability          ✦   seamlessness
✦   standards compliance   ✦   extensibility      ✦   portability          ✦   serviceability
✦   process capabilities   ✦   fidelity            ✦   precision            ✦   securability
✦   compatibility          ✦   flexibility         ✦   predictability       ✦   simplicity
✦   composability          ✦   installability     ✦   recoverability       ✦   stability
OBJECTIVE ATTRIBUTES
✦   accessibility          ✦   configurability     ✦   integrity            ✦   relevance         ✦   survivability
✦   accountability         ✦   correctness        ✦   interchangeability   ✦   reliability       ✦   sustainability
✦   accuracy               ✦   customizability    ✦   interoperability     ✦   repeatability     ✦   tailorability
✦   adaptability           ✦   degradability      ✦   learnability         ✦   reproducibility   ✦   testability
✦   administrability       ✦   demonstrability    ✦   maintainability      ✦   responsiveness    ✦   timeliness
✦   affordability          ✦   dependability      ✦   manageability        ✦   reusability       ✦   understandability
✦   agility                ✦   deployability      ✦   mobility             ✦   robustness        ✦   usability
✦   auditability           ✦   distributability   ✦   modularity           ✦   safety            ✦   ...
✦   availability           ✦   durability         ✦   nomadicity           ✦   scalability
✦   credibility            ✦   evolvability       ✦   operability          ✦   seamlessness
✦   standards compliance   ✦   extensibility      ✦   portability          ✦   serviceability
✦   process capabilities   ✦   fidelity            ✦   precision            ✦   securability
✦   compatibility          ✦   flexibility         ✦   predictability       ✦   simplicity
✦   composability          ✦   installability     ✦   recoverability       ✦   stability
SUBJECTIVE ATTRIBUTES?
✦   accessibility          ✦   configurability     ✦   integrity            ✦   relevance         ✦   survivability
✦   accountability         ✦   correctness        ✦   interchangeability   ✦   reliability       ✦   sustainability
✦   accuracy               ✦   customizability    ✦   interoperability     ✦   repeatability     ✦   tailorability
✦   adaptability           ✦   degradability      ✦   learnability         ✦   reproducibility   ✦   testability
✦   administrability       ✦   demonstrability    ✦   maintainability      ✦   responsiveness    ✦   timeliness
✦   affordability          ✦   dependability      ✦   manageability        ✦   reusability       ✦   understandability
✦   agility                ✦   deployability      ✦   mobility             ✦   robustness        ✦   usability
✦   auditability           ✦   distributability   ✦   modularity           ✦   safety            ✦   ...
✦   availability           ✦   durability         ✦   nomadicity           ✦   scalability
✦   credibility            ✦   evolvability       ✦   operability          ✦   seamlessness
✦   standards compliance   ✦   extensibility      ✦   portability          ✦   serviceability
✦   process capabilities   ✦   fidelity            ✦   precision            ✦   securability
✦   compatibility          ✦   flexibility         ✦   predictability       ✦   simplicity
✦   composability          ✦   installability     ✦   recoverability       ✦   stability
WHAT DOES GOOD
 CODE LOOK LIKE?
OBFUSCATION?

                                                                C

void qs(int l[], int m, int n) { int kk, i, j, k; if (m < n)
{ k = cp(m,n); s(&l[m], &l[k]); kk = l[m]; i = m + 1; j = n;
while(i <= j) { while((i <= n) && (l[i] <= kk)) i++; while((j
>= m) && (l[j] > kk)) j--; if (i < j) s(&l[i], &l[j]); } s(&l
[m], &l[j]); qs(l, m, j-1); qs(l, j+1, n); }}
CODE?
                                                  C
void qs(int l[], int m, int n) {
! int kk, i, j, k;

!   if   (m < n) {
!   !    k = cp(m,n);
!   !    s(&l[m], &l[k]);
!   !    kk = l[m];
!   !    i = m + 1; j = n;
!   !    while(i <= j) {
!   !    ! while((i <= n) && (l[i] <= kk)) i++;
!   !    ! while((j >= m) && (l[j] > kk)) j--;
!   !    ! if (i < j) s(&l[i], &l[j]);
!   !    }
!   !
!   !    s(&l[m], &l[j]);
!   !
!   !    qs(l, m, j-1);
!   !    qs(l, j+1, n);
!   }
}
ART?
                                                      C
void quicksort(int list[], int m, int n) {
! int key, i, j, k;

!   if   (m < n) {
!   !    k = choose_pivot(m,n);
!   !    swap(&list[m], &list[k]);
!   !    key = list[m];
!   !    i = m + 1; j = n;
!   !    while(i <= j) {
!   !    ! while((i <= n) && (list[i] <= key)) i++;
!   !    ! while((j >= m) && (list[j] > key)) j--;
!   !    ! if (i < j) swap(&list[i], &list[j]);
!   !    }
!   !
!   !    swap(&list[m], &list[j]);
!   !
!   !    quicksort(list, m, j-1);
!   !    quicksort(list, j+1, n);
!   }
}
ABSORPTION?

                                                             HASKELL

qs []     = []
qs (x:xs) = qs (filter (< x) xs) ++ [x] ++ qs (filter (>= x) xs)
CONDITIONALS...
                                                                C#




                  class Employee ...
                    int payAmount() {
    Employee          switch(type) {
– monthlySalary         case ENGINEER:
– bonus                   return monthlySalary;
– totalSales            case SALESMAN:
– type
                          return monthlySalary + 0.1 * totalSales;
+ payAmount             case MANAGER:
                          return monthlySalary + bonus;
                        default:
                          throw Exception("Incorrect Employee");
                      }
                    }
... V.S. POLYMORPHISM
                                                                   C#
                    abstract class Employee ...
   Employee           abstract int payAmount();
– monthlySalary
+ payAmount         class Engineer: Employee ...
                      int payAmount() {
         Engineer       return monthlySalary;
     + payAmount      }
         Manager    class Salesman: Employee ...
     – bonus          int payAmount() {
     + payAmount        return monthlySalary + 0.1 * totalSales;
                      }
         Salesman
     – totalSales   class Manager: Employee ...
     + payAmount      int payAmount() {
                        return monthlySalary + bonus;
                      }
IS GOOD CODE
DIFFERENT IN FORM?
SOFTWARE DESIGN

Object Oriented Design is more than just drawing diagrams:

• Good    OO designers rely on lots of experience
• OO     systems exhibit recurring structures that promote:

         abstraction   flexibility   modularity   elegance

• Therein   lies valuable design knowledge
• This   reusable knowledge is captured through patterns
ALEXANDER’S PATTERN
... a recognized good solution for a recurrent problem,
which balances all relevant forces, optimizing the tradeoffs
for a specific purpose.


            P = ⟨ problem, forces, solution ⟩

... are prescriptive rather than descriptive. It drives the
designer to make a choice based on the forces and the
resulting consequences.
PATTERNS ARE EVERYWHERE




         ... in nature ...
PATTERNS ARE EVERYWHERE




         ... in music ...
PATTERNS ARE EVERYWHERE




        ... in architecture ...
PATTERNS ARE EVERYWHERE




         ... in art ...
PATTERNS ARE EVERYWHERE




        ... in mathematics ...
WHY PATTERNS?


“   Patterns analyze and formalize empirical knowledge in
    search for stronger invariants, allowing rational design
    choices and uncovering newer abstractions.
LIGHT ON TWO SIDES **
Once the building's major rooms are in position, we have to fix its
actual shape...




                                      “       When they have a
                                       choice, people will always
                                       gravitate to those rooms which
                                       have light on two sides, and
                                       leave the rooms which are lit
                                       only from one side unused and
                                       empty.
LIGHT ON TWO SIDES **
Locate each room so that it has outdoor space outside it on at
least two sides, and then place windows in these outdoor walls
so that natural light falls into every room from more than one
direction.
DESIGN PATTERNS
• Gamma et al. Design Patterns: Elements of Reusable Object-Oriented Software.
• It presents 3 categories of 23 interconnected patterns on OO design.
• It’s taught worldwide in CS/SE as an introductory book on software architecture
  and design:

          • Singleton,             • Proxy,                • Decorator,
          • Composite,             • State,                • Adapter,
          • Façade,                • Bridge,               • Flyweight,
          • Abstract Factory,      • Factory method,       • ...

 Still:
     • They have a context which may need to be adapted.
     • They are abstractions, not out of the box components.
ARCHITECTURAL PATTERNS
• Bucshmann et al. series of Pattern Oriented Software Architecture
• Higher-level concerns: architecture v.s. design.
• Decoupled from OO compared to the GoF book (different domain).

    • Layers,                              • Reflection,
    • Pipes and Filters,                   • Whole-part,
    • Blackboard,                          • Master-slave,
    • Broker,                              • Proxy,
    • Model-View-Controller,               • Command Processor,
    • Presentation-Abstraction-Control,    • View Handler,
    • Microkernel,                         • ...
DOMAIN-SPECIFIC
There are several books and pattern languages that focus on
specific domains such as:
  • Distributed systems,                      • Documentation,
  • Adaptive systems,                         • Frameworks,
  • Requirements engineering,                 • Interaction design,
  • Sociology,                                • Pedagogical,
  • Psychology,                               • ...


Some are even about patterns themselves:
   • A Pattern Language for Patern Writing,
   • Meta-Patterns.
ANATOMY OF A PATTERN
Name. Usually a “catchy” noun that             restrict the pattern to a narrow list of
describes what the pattern “builds.”           specifics.
Aliases. Also known as...                      Resulting Context. Include the new
                                               problems that appear as a result of applying
Sketch. A metaphorical figure.                  the pattern that may require new patterns
Context. Describe the setting for the          for their resolution.
problem. Include a description of the target   Rationale. Explain the rationale behind the
user.                                          solution. Convince the reader. Tell stories!
Forces. Why the problem is not trivial.        Share your expertise.
Discuss other possible solutions and why       Known Uses. Briefly list or describe places
they won’t work.                               where the pattern is used.
Problem. Unbiased by the solution.             Related Patterns. Briefly describe any
Solution. Include enough detail so the user    related patterns and their relationships to
can implement the solution, but don’t          this pattern.
EXTENDED ANATOMY...
Name. Usually a “catchy” noun that             restrict the pattern to a narrow list of
describes what the pattern “builds.”           specifics.
Aliases. Also known as...                      Resulting Context. Include the new
                                               problems that appear as a result of applying
Sketch. A metaphorical figure.                  the pattern that may require new patterns
Context. Describe the setting for the          for their resolution.
problem. Include a description of the target   Rationale. Explain the rationale behind the
user.                                          solution. Convince the reader. Tell stories!
Forces. Why the problem is not trivial.        Share your expertise.
Discuss other possible solutions and why       Known Uses. Briefly list or describe places
they won’t work.                               where the pattern is used.
Problem. Unbiased by the solution.             Related Patterns. Briefly describe any
Solution. Include enough detail so the user    related patterns and their relationships to
can implement the solution, but don’t          this pattern.
EXAMPLE
OBSERVER PATTERN
Also known as
Subject Observer, Publish-Subscribe, Callback.

Intent
Define a one-to-many dependency between objects so that when
one object (called the subject) changes state, all its dependents
(called the observers) are notified and updated automatically.


Motivation
The need to maintain consistency between related objects without
making classes tightly coupled
SKETCH




(doesn’t know the observers)
APPLICABILITY

Use the Observer pattern in any of the following situations:
• When an abstraction has two aspects, one dependent on the other.
  Encapsulating these aspects in separate objects lets you vary and reuse
  them independently.
• When a change to one object requires changing others
• When an object should be able to notify other objects without making
  assumptions about those objects
STRUCTURE

                             abstract class
abstract class
                              or interface
PARTICIPANTS
Subject
  • Keeps track of its observers
  • Provides an interface for attaching and detaching Observer objects
Observer
  • Defines an interface for update notification
ConcreteSubject
  • The object being observed
  • Stores state of interest to ConcreteObserver objects
  • Sends a notification to its observers when its state changes
ConcreteObserver
  • The observing object
  • Stores state that should stay consistent with the subject's
  • Implements the Observer update interface to keep its state consistent with the subject's
COLLABORATIONS
CONSEQUENCES
+ Minimal coupling between the Subject and the Observer
   •   Can reuse subjects without reusing their observers and vice versa
   •   Observers can be added without modifying the subject
   •   All subject knows is its list of observers
   •   Subject does not need to know the concrete class of an observer, just that each observer implements the
       update interface
   •   Subject and observer can belong to different abstraction layers

+ Support for event broadcasting
   •   Subject sends notification to all subscribed observers
   •   Observers can be added/removed at any time

– Possible cascading of notifications
   •   Observers are not necessarily aware of each other and must be careful about triggering updates

– Simple update interface requires observers to deduce changed item
IMPLEMENTATION
•   How does the subject keep track of its observers?
    •   Array, linked list
•   What if an observer wants to observe more than one subject?
    •   Have the subject tell the observer who it is via the update interface
•   Who triggers the update?
    •   The subject whenever its state changes
    •   The observers after they cause one or more state changes
    •   Some third party object(s)
•   Make sure the subject updates its state before sending out notifications
•   How much info about the change should the subject send to the observers?
    •   Push Model - Lots
    •   Pull Model - Very Little
IMPLEMENTATION
•   Can the observers subscribe to specific events of interest?
    •   If so, it's publish-subscribe
•   Can an observer also be a subject?
    •   Yes!
•   What if an observer wants to be notified only after several subjects have
    changed state?
    •   Use an intermediary object which acts as a mediator
    •   Subjects send notifications to the mediator object which performs any necessary
        processing before notifying the observers
KNOWN USES

• Smalltalk   Model/View/Controller user interface framework
  • Model     = Subject
  • View   = Observer
  • Controller   is whatever object changes the state of the
    subject
• Java   1.1 AWT/Swing Event Model
RELATED PATTERNS

• Mediator. To   encapsulate complex update semantics.
JAVA BUILT-IN SUPPORT
interface java.util.Observer
• void   update(Observable o, Object arg)

class java.util.Observable (=Subject)
• void   addObserver(Observer o)
• void   deleteObserver(Observer o)
• void   setChanged()
• void   notifyObservers(Object arg)
A CONCRETE SUBJECT
                                                       JAVA
public class ConcreteSubject extends Observable ...
  private String name;
  private float price;

  public ConcreteSubject(String name, float price) {
    this.name = name;
    this.price = price;
  }

  public String getName() { return name; }

  public float getPrice() { return price; }

  public void setPrice(float price) {
    this.price = price;
    setChanged();
    notifyObservers(price);
  }
A CONCRETE OBSERVER
                                                        JAVA
public class ConcreteObserver implements Observer ...
  private float price;

  public ConcreteObserver() {
    price = 0;
  }

  public void update(Observable obj, Object arg) {
    price = (Float) arg;
  }

  public getPrice() { return price; }
TEST SCENARIO

                                                             JAVA
@Test
public void test1() {
   ConcreteSubject s = new ConcreteSubject("Corn", 1.29f);
   ConcreteObserver o = new ConcreteObserver();
   s.addObserver(o);
   s.setPrice(4.57f);
   assertEquals(4.57f, o.getPrice());
}
?

Más contenido relacionado

Último

Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Último (20)

Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

Destacado

AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Destacado (20)

AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 

Design Patterns: A Lightweight Introduction

  • 1. DESIGN PATTERNS hugo sereno ferreira . joão pascoal faria . jorge barbosa . nuno flores A L IG H TW E I G H T INTROD UC TION
  • 2. ARCHITECTURE ... a cabana seems simple ...
  • 3. ARCHITECTURE ... easier than an house ...
  • 4. ARCHITECTURE ... child’s play next to a building ...
  • 5. ARCHITECTURE ... but nothing compared to a city!
  • 6. WHERE’S THE DIFFERENCES? • Size. From a small cabana, to a large city. • Cost. From less than €1k, to more than €1.000.000k • Time. Taking a day, to evolving through centuries. • Process. Doing as an hobby v.s. planning. • Skills. From a layman, to highly qualified professionals. • Risk. Vacations v.s. a population of millions. • ...
  • 7. FINDING THE BEST DESIGN time – – + scope – cost – + quality
  • 8. DEFINITION “ Architecture is the process and product of planning, designing and constructing physical form, space and ambience that reflect functional, technical, social, and aesthetic considerations. Wikipedia
  • 9. SOFTWARE? “ ... the process and product of planning, designing and constructing logical form, space and ambience that reflect functional, technical, social, and aesthetic considerations.
  • 10. QUALITY IN SOFTWARE ✦ accessibility ✦ configurability ✦ integrity ✦ relevance ✦ survivability ✦ accountability ✦ correctness ✦ interchangeability ✦ reliability ✦ sustainability ✦ accuracy ✦ customizability ✦ interoperability ✦ repeatability ✦ tailorability ✦ adaptability ✦ degradability ✦ learnability ✦ reproducibility ✦ testability ✦ administrability ✦ demonstrability ✦ maintainability ✦ responsiveness ✦ timeliness ✦ affordability ✦ dependability ✦ manageability ✦ reusability ✦ understandability ✦ agility ✦ deployability ✦ mobility ✦ robustness ✦ usability ✦ auditability ✦ distributability ✦ modularity ✦ safety ✦ ... ✦ availability ✦ durability ✦ nomadicity ✦ scalability ✦ credibility ✦ evolvability ✦ operability ✦ seamlessness ✦ standards compliance ✦ extensibility ✦ portability ✦ serviceability ✦ process capabilities ✦ fidelity ✦ precision ✦ securability ✦ compatibility ✦ flexibility ✦ predictability ✦ simplicity ✦ composability ✦ installability ✦ recoverability ✦ stability
  • 11. OBJECTIVE ATTRIBUTES ✦ accessibility ✦ configurability ✦ integrity ✦ relevance ✦ survivability ✦ accountability ✦ correctness ✦ interchangeability ✦ reliability ✦ sustainability ✦ accuracy ✦ customizability ✦ interoperability ✦ repeatability ✦ tailorability ✦ adaptability ✦ degradability ✦ learnability ✦ reproducibility ✦ testability ✦ administrability ✦ demonstrability ✦ maintainability ✦ responsiveness ✦ timeliness ✦ affordability ✦ dependability ✦ manageability ✦ reusability ✦ understandability ✦ agility ✦ deployability ✦ mobility ✦ robustness ✦ usability ✦ auditability ✦ distributability ✦ modularity ✦ safety ✦ ... ✦ availability ✦ durability ✦ nomadicity ✦ scalability ✦ credibility ✦ evolvability ✦ operability ✦ seamlessness ✦ standards compliance ✦ extensibility ✦ portability ✦ serviceability ✦ process capabilities ✦ fidelity ✦ precision ✦ securability ✦ compatibility ✦ flexibility ✦ predictability ✦ simplicity ✦ composability ✦ installability ✦ recoverability ✦ stability
  • 12. SUBJECTIVE ATTRIBUTES? ✦ accessibility ✦ configurability ✦ integrity ✦ relevance ✦ survivability ✦ accountability ✦ correctness ✦ interchangeability ✦ reliability ✦ sustainability ✦ accuracy ✦ customizability ✦ interoperability ✦ repeatability ✦ tailorability ✦ adaptability ✦ degradability ✦ learnability ✦ reproducibility ✦ testability ✦ administrability ✦ demonstrability ✦ maintainability ✦ responsiveness ✦ timeliness ✦ affordability ✦ dependability ✦ manageability ✦ reusability ✦ understandability ✦ agility ✦ deployability ✦ mobility ✦ robustness ✦ usability ✦ auditability ✦ distributability ✦ modularity ✦ safety ✦ ... ✦ availability ✦ durability ✦ nomadicity ✦ scalability ✦ credibility ✦ evolvability ✦ operability ✦ seamlessness ✦ standards compliance ✦ extensibility ✦ portability ✦ serviceability ✦ process capabilities ✦ fidelity ✦ precision ✦ securability ✦ compatibility ✦ flexibility ✦ predictability ✦ simplicity ✦ composability ✦ installability ✦ recoverability ✦ stability
  • 13. WHAT DOES GOOD CODE LOOK LIKE?
  • 14. OBFUSCATION? C void qs(int l[], int m, int n) { int kk, i, j, k; if (m < n) { k = cp(m,n); s(&l[m], &l[k]); kk = l[m]; i = m + 1; j = n; while(i <= j) { while((i <= n) && (l[i] <= kk)) i++; while((j >= m) && (l[j] > kk)) j--; if (i < j) s(&l[i], &l[j]); } s(&l [m], &l[j]); qs(l, m, j-1); qs(l, j+1, n); }}
  • 15. CODE? C void qs(int l[], int m, int n) { ! int kk, i, j, k; ! if (m < n) { ! ! k = cp(m,n); ! ! s(&l[m], &l[k]); ! ! kk = l[m]; ! ! i = m + 1; j = n; ! ! while(i <= j) { ! ! ! while((i <= n) && (l[i] <= kk)) i++; ! ! ! while((j >= m) && (l[j] > kk)) j--; ! ! ! if (i < j) s(&l[i], &l[j]); ! ! } ! ! ! ! s(&l[m], &l[j]); ! ! ! ! qs(l, m, j-1); ! ! qs(l, j+1, n); ! } }
  • 16. ART? C void quicksort(int list[], int m, int n) { ! int key, i, j, k; ! if (m < n) { ! ! k = choose_pivot(m,n); ! ! swap(&list[m], &list[k]); ! ! key = list[m]; ! ! i = m + 1; j = n; ! ! while(i <= j) { ! ! ! while((i <= n) && (list[i] <= key)) i++; ! ! ! while((j >= m) && (list[j] > key)) j--; ! ! ! if (i < j) swap(&list[i], &list[j]); ! ! } ! ! ! ! swap(&list[m], &list[j]); ! ! ! ! quicksort(list, m, j-1); ! ! quicksort(list, j+1, n); ! } }
  • 17. ABSORPTION? HASKELL qs [] = [] qs (x:xs) = qs (filter (< x) xs) ++ [x] ++ qs (filter (>= x) xs)
  • 18. CONDITIONALS... C# class Employee ... int payAmount() { Employee switch(type) { – monthlySalary case ENGINEER: – bonus return monthlySalary; – totalSales case SALESMAN: – type return monthlySalary + 0.1 * totalSales; + payAmount case MANAGER: return monthlySalary + bonus; default: throw Exception("Incorrect Employee"); } }
  • 19. ... V.S. POLYMORPHISM C# abstract class Employee ... Employee abstract int payAmount(); – monthlySalary + payAmount class Engineer: Employee ... int payAmount() { Engineer return monthlySalary; + payAmount } Manager class Salesman: Employee ... – bonus int payAmount() { + payAmount return monthlySalary + 0.1 * totalSales; } Salesman – totalSales class Manager: Employee ... + payAmount int payAmount() { return monthlySalary + bonus; }
  • 21. SOFTWARE DESIGN Object Oriented Design is more than just drawing diagrams: • Good OO designers rely on lots of experience • OO systems exhibit recurring structures that promote: abstraction flexibility modularity elegance • Therein lies valuable design knowledge • This reusable knowledge is captured through patterns
  • 22. ALEXANDER’S PATTERN ... a recognized good solution for a recurrent problem, which balances all relevant forces, optimizing the tradeoffs for a specific purpose. P = ⟨ problem, forces, solution ⟩ ... are prescriptive rather than descriptive. It drives the designer to make a choice based on the forces and the resulting consequences.
  • 23. PATTERNS ARE EVERYWHERE ... in nature ...
  • 24. PATTERNS ARE EVERYWHERE ... in music ...
  • 25. PATTERNS ARE EVERYWHERE ... in architecture ...
  • 26. PATTERNS ARE EVERYWHERE ... in art ...
  • 27. PATTERNS ARE EVERYWHERE ... in mathematics ...
  • 28. WHY PATTERNS? “ Patterns analyze and formalize empirical knowledge in search for stronger invariants, allowing rational design choices and uncovering newer abstractions.
  • 29. LIGHT ON TWO SIDES ** Once the building's major rooms are in position, we have to fix its actual shape... “ When they have a choice, people will always gravitate to those rooms which have light on two sides, and leave the rooms which are lit only from one side unused and empty.
  • 30. LIGHT ON TWO SIDES ** Locate each room so that it has outdoor space outside it on at least two sides, and then place windows in these outdoor walls so that natural light falls into every room from more than one direction.
  • 31. DESIGN PATTERNS • Gamma et al. Design Patterns: Elements of Reusable Object-Oriented Software. • It presents 3 categories of 23 interconnected patterns on OO design. • It’s taught worldwide in CS/SE as an introductory book on software architecture and design: • Singleton, • Proxy, • Decorator, • Composite, • State, • Adapter, • Façade, • Bridge, • Flyweight, • Abstract Factory, • Factory method, • ... Still: • They have a context which may need to be adapted. • They are abstractions, not out of the box components.
  • 32. ARCHITECTURAL PATTERNS • Bucshmann et al. series of Pattern Oriented Software Architecture • Higher-level concerns: architecture v.s. design. • Decoupled from OO compared to the GoF book (different domain). • Layers, • Reflection, • Pipes and Filters, • Whole-part, • Blackboard, • Master-slave, • Broker, • Proxy, • Model-View-Controller, • Command Processor, • Presentation-Abstraction-Control, • View Handler, • Microkernel, • ...
  • 33. DOMAIN-SPECIFIC There are several books and pattern languages that focus on specific domains such as: • Distributed systems, • Documentation, • Adaptive systems, • Frameworks, • Requirements engineering, • Interaction design, • Sociology, • Pedagogical, • Psychology, • ... Some are even about patterns themselves: • A Pattern Language for Patern Writing, • Meta-Patterns.
  • 34. ANATOMY OF A PATTERN Name. Usually a “catchy” noun that restrict the pattern to a narrow list of describes what the pattern “builds.” specifics. Aliases. Also known as... Resulting Context. Include the new problems that appear as a result of applying Sketch. A metaphorical figure. the pattern that may require new patterns Context. Describe the setting for the for their resolution. problem. Include a description of the target Rationale. Explain the rationale behind the user. solution. Convince the reader. Tell stories! Forces. Why the problem is not trivial. Share your expertise. Discuss other possible solutions and why Known Uses. Briefly list or describe places they won’t work. where the pattern is used. Problem. Unbiased by the solution. Related Patterns. Briefly describe any Solution. Include enough detail so the user related patterns and their relationships to can implement the solution, but don’t this pattern.
  • 35. EXTENDED ANATOMY... Name. Usually a “catchy” noun that restrict the pattern to a narrow list of describes what the pattern “builds.” specifics. Aliases. Also known as... Resulting Context. Include the new problems that appear as a result of applying Sketch. A metaphorical figure. the pattern that may require new patterns Context. Describe the setting for the for their resolution. problem. Include a description of the target Rationale. Explain the rationale behind the user. solution. Convince the reader. Tell stories! Forces. Why the problem is not trivial. Share your expertise. Discuss other possible solutions and why Known Uses. Briefly list or describe places they won’t work. where the pattern is used. Problem. Unbiased by the solution. Related Patterns. Briefly describe any Solution. Include enough detail so the user related patterns and their relationships to can implement the solution, but don’t this pattern.
  • 37. OBSERVER PATTERN Also known as Subject Observer, Publish-Subscribe, Callback. Intent Define a one-to-many dependency between objects so that when one object (called the subject) changes state, all its dependents (called the observers) are notified and updated automatically. Motivation The need to maintain consistency between related objects without making classes tightly coupled
  • 39. APPLICABILITY Use the Observer pattern in any of the following situations: • When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently. • When a change to one object requires changing others • When an object should be able to notify other objects without making assumptions about those objects
  • 40. STRUCTURE abstract class abstract class or interface
  • 41. PARTICIPANTS Subject • Keeps track of its observers • Provides an interface for attaching and detaching Observer objects Observer • Defines an interface for update notification ConcreteSubject • The object being observed • Stores state of interest to ConcreteObserver objects • Sends a notification to its observers when its state changes ConcreteObserver • The observing object • Stores state that should stay consistent with the subject's • Implements the Observer update interface to keep its state consistent with the subject's
  • 43. CONSEQUENCES + Minimal coupling between the Subject and the Observer • Can reuse subjects without reusing their observers and vice versa • Observers can be added without modifying the subject • All subject knows is its list of observers • Subject does not need to know the concrete class of an observer, just that each observer implements the update interface • Subject and observer can belong to different abstraction layers + Support for event broadcasting • Subject sends notification to all subscribed observers • Observers can be added/removed at any time – Possible cascading of notifications • Observers are not necessarily aware of each other and must be careful about triggering updates – Simple update interface requires observers to deduce changed item
  • 44. IMPLEMENTATION • How does the subject keep track of its observers? • Array, linked list • What if an observer wants to observe more than one subject? • Have the subject tell the observer who it is via the update interface • Who triggers the update? • The subject whenever its state changes • The observers after they cause one or more state changes • Some third party object(s) • Make sure the subject updates its state before sending out notifications • How much info about the change should the subject send to the observers? • Push Model - Lots • Pull Model - Very Little
  • 45. IMPLEMENTATION • Can the observers subscribe to specific events of interest? • If so, it's publish-subscribe • Can an observer also be a subject? • Yes! • What if an observer wants to be notified only after several subjects have changed state? • Use an intermediary object which acts as a mediator • Subjects send notifications to the mediator object which performs any necessary processing before notifying the observers
  • 46. KNOWN USES • Smalltalk Model/View/Controller user interface framework • Model = Subject • View = Observer • Controller is whatever object changes the state of the subject • Java 1.1 AWT/Swing Event Model
  • 47. RELATED PATTERNS • Mediator. To encapsulate complex update semantics.
  • 48. JAVA BUILT-IN SUPPORT interface java.util.Observer • void update(Observable o, Object arg) class java.util.Observable (=Subject) • void addObserver(Observer o) • void deleteObserver(Observer o) • void setChanged() • void notifyObservers(Object arg)
  • 49. A CONCRETE SUBJECT JAVA public class ConcreteSubject extends Observable ... private String name; private float price; public ConcreteSubject(String name, float price) { this.name = name; this.price = price; } public String getName() { return name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; setChanged(); notifyObservers(price); }
  • 50. A CONCRETE OBSERVER JAVA public class ConcreteObserver implements Observer ... private float price; public ConcreteObserver() { price = 0; } public void update(Observable obj, Object arg) { price = (Float) arg; } public getPrice() { return price; }
  • 51. TEST SCENARIO JAVA @Test public void test1() { ConcreteSubject s = new ConcreteSubject("Corn", 1.29f); ConcreteObserver o = new ConcreteObserver(); s.addObserver(o); s.setPrice(4.57f); assertEquals(4.57f, o.getPrice()); }
  • 52. ?