SlideShare ist ein Scribd-Unternehmen logo
1 von 52
Downloaden Sie, um offline zu lesen
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());
}
?

Weitere ähnliche Inhalte

Kürzlich hochgeladen

The Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingThe Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingSelcen Ozturkcan
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 

Kürzlich hochgeladen (20)

The Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central BankingThe Evolution of Money: Digital Transformation and CBDCs in Central Banking
The Evolution of Money: Digital Transformation and CBDCs in Central Banking
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

Empfohlen

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
 

Empfohlen (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. ?