๐ŸŽฏ Lecture 12 ยท The most important lecture for Q3

Design Patterns & Strategy Pattern

Question 3 (15-24 marks) ููŠ ูƒู„ ุงู…ุชุญุงู† final ุจูŠูƒูˆู† ุนู† Strategy Pattern. ู‡ุชุจู†ูŠ full UML diagram + write all Java code. ุฑูƒุฒ ุฌุฏุงู‹.

8
Chapters
23
GoF Patterns
โญ
Strategy = Q3
8
Exam Qs
01

Introduction to Design Patterns

ุงู„ู€ pattern = recurring solution ู„ู€ common problem ููŠ specific context.

๐Ÿ“œ History & Origin
  • Based on work by Christopher Alexander (Architect) on building homes/towns.
  • Gang of Four (GoF) book โ€” 1995, by Gamma, Helm, Johnson, Vlissides.
  • Described 23 recurring software designs.
"Each pattern describes a problem which occurs over and over again, and then describes the core of the solution, in such a way that you can use this solution a million times over, without ever doing it in the same way twice."
โ€” Christopher Alexander, A Pattern Language, 1977
โš ๏ธ Motivating Problem โ€” Sort Method Evolution

ุชุจุฏุฃ ุจูƒุชุงุจุฉ ArrayList ููŠู‡ sort() ุจู€ bubble sort. ุชุบูŠุฑู‡ ู„ู€ merge sort. ุชุญุงูˆู„ ุงู„ุงุชู†ูŠู† ุจู€ if/else:

public class ArrayList<T> {
  public void sort(int sortChoice) {
    if (sortChoice == 1) { /* merge sort */ }
    if (sortChoice == 2) { /* bubble sort */ }
  }
}
๐Ÿ”ด What's wrong?
  1. Violates OCP โ€” for any new algorithm, you modify the class.
  2. Every change affects all clients that use it.
  3. What about future algorithms you don't know yet? You'll keep editing.
๐Ÿ’ก Uncle Bob's wisdom"When writing a class, ensure that when you need to extend its behavior you don't have to change the class but to extend it."
02

GoF โ€” 23 Design Patterns

ุชู†ู‚ุณู… ู„ู€ 3 categories.

๐Ÿ—๏ธ Creational (5)

About object creation

  • Abstract Factory
  • Builder
  • Factory Method
  • Prototype

๐Ÿ›๏ธ Structural (7)

About composition

  • Bridge
  • Composite
  • Decorator
  • Faรงade
  • Flyweight
  • Proxy

๐ŸŽญ Behavioral (11)

About interaction

  • Chain of Responsibility
  • Command
  • Interpreter
  • Iterator
  • Mediator
  • Memento
  • State
  • Visitor
โš ๏ธ ุงู„ู„ูŠ ุจูŠุชุณุฃู„ ุนู„ูŠู‡ู… ููŠ ุงู„ู€ examsStrategy (Q3 in every exam), Observer / Publish-Subscribe (Q1.17 Fall 2021-22 / Winter 2021), Adapter (Q3 Winter 2023), Template Method (Q1.08 Winter 2025), Singleton (common interview question).
03

4 Essential Elements of a Pattern

ูƒู„ design pattern ู„ู‡ 4 essential elements.

1. Name

Handle ู„ูˆุตู problem ยท solution ยท consequences. Increases design vocabulary.

2. Problem

ู…ุชู‰ ู†ุทุจู‚ ุงู„ู€ pattern + the context + preconditions.

3. Solution

Elements: design ยท relationships ยท responsibilities ยท collaborations.

4. Consequences

ุงู„ู€ trade-offs ูˆุงู„ู€ results ู…ู† ุชุทุจูŠู‚ ุงู„ู€ pattern.

04

Java GUI โ€” Swing & AWT

ุงู„ู€ Java libraries ู„ู„ู€ GUI. ุงู„ู€ AWT ู‡ูŠ ุงู„ุฃุณุงุณุŒ ุงู„ู€ Swing ุจูŠุฑุซ ู…ู†ู‡ุง.

๐ŸชŸ Hierarchy
  • AWT (java.awt) โ€” old, OS-dependent rendering.
  • Swing (javax.swing) โ€” new, classes start with J (e.g., JFrame, JPanel, JButton).

Sample Java GUI Composition

JFrame (Window)
โ†“ contains
JPanel ร— N
โ†“ contains
J* Components (JButton, JLabel, ...)
+ organized by
LayoutManager (FlowLayout, GridLayout, BorderLayout)
+ react via
ActionListener
๐Ÿ’ป Tic-Tac-Toe Example
public class TicTacToe1 extends JFrame {
  public TicTacToe1() {
    setTitle("Tic Tac Toe");
    setSize(310, 210);
    setLayout(new GridLayout(2, 1));

    JLabel messageLabel = new JLabel("It is X turn.");
    JPanel msgPanel = new JPanel(new FlowLayout());
    msgPanel.add(messageLabel);

    JPanel gamePanel = new JPanel(new GridLayout(3, 3));
    for (int i = 0; i < 9; i++) {
      gamePanel.add(new JButton(""));
    }
    add(msgPanel); add(gamePanel);
    setVisible(true);
  }
}
๐Ÿ‘‚ Event Listeners

ุงู„ู€ AWT/Swing components ุจุชู†ุดุฑ events. ุงู„ู€ EventListeners ุจุชุดุชุฑูƒ ููŠู‡ุง.

ComponentEventListener
JButtonActionEventActionListener
JComponentMouseEventMouseListener
JComponentKeyEventKeyListener
// Adding listener with anonymous inner class
JButton again = new JButton("New game");
again.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    newGame();
  }
});
05

JavaFX โ€” Modern UI

Swing ู‡ูˆ ุงู„ู€ Legacy. JavaFX ู‡ูˆ ุงู„ู€ Modern Industry Standard.

โš–๏ธ Swing vs JavaFX Comparison
FeatureSwing (Legacy)JavaFX (Modern)
Top-Level ContainerJFrameStage
ContentJPanel / ContentPaneScene
Component BaseJComponentNode
HierarchyFlat: Frameโ†’Panelโ†’CompScene Graph: Stageโ†’Sceneโ†’Rootโ†’Nodes
LayoutsetLayout()setRoot(newParent)
StylingJava codeCSS
Graphics EngineCPU (software)GPU accelerated
Layout StrategyFlowLayout, GridLayout, BorderLayoutHBox, VBox, GridPane, StackPane
Visual DesignCode onlyFXML + Scene Builder
MultimediaLimited3D, Video, Audio, WebKit built-in
EventsAnonymous inner classesLambda expressions
06

Strategy Pattern โญโญโญ

ุงู„ู€ Pattern ุงู„ุฃู‡ู… ููŠ ุงู„ู€ course. Q3 ููŠ ูƒู„ final fingerprint exam.

Behavioral Pattern ยท GoF

๐ŸŽฏ Strategy

๐Ÿ“ Context

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

โ“ Problem

Allow different behaviors without changing the class of an object. Strategy/Algorithm can change at runtime within the same class.

โœ… Solution

Represent each strategy by a separate class. Each strategy class implements the appropriate algorithm. At runtime, a class can change its strategy.

๐ŸŽฏ When to Use Strategy
  • Many related classes differ only in behavior.
  • You need different variants of an algorithm.
  • Algorithm uses data clients shouldn't know about.
  • A class has many behaviors as multiple conditional statements โ€” move them into Strategy classes.
๐Ÿ’ก Key Triggerู„ูˆ ููŠ ูƒูˆุฏ ููŠู‡ if/else chain ุฃูˆ switch ุจูŠุฎุชุงุฑ between behaviors โ†’ ููƒุฑ ููŠ Strategy.
07

Strategy Pattern โ€” UML Structure

3 elements: Context ยท Strategy interface ยท Concrete Strategies.

๐Ÿ“ UML Class Diagram
       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
       โ”‚     Context       โ”‚ โ—‡โ”€ โ”€โ”€โ”€โ”€โ†’โ”‚  ยซinterfaceยป Strategy  โ”‚
       โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค strategyโ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
       โ”‚ -strategy:Strategyโ”‚         โ”‚ +algorithm() :          โ”‚
       โ”‚ +contextOp()      โ”‚         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                    โ–ณ
                                                โ”‚ implements
                          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                          โ”‚                     โ”‚                     โ”‚
              โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
              โ”‚ ConcreteStrategyA โ”‚  โ”‚ ConcreteStrategyB โ”‚  โ”‚ ConcreteStrategyC โ”‚
              โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค  โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค  โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
              โ”‚ +algorithm()      โ”‚  โ”‚ +algorithm()      โ”‚  โ”‚ +algorithm()      โ”‚
              โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  • Context: holds reference to Strategy. Delegates algorithm work to it.
  • Strategy: interface/abstract class defining the algorithm signature.
  • ConcreteStrategies: each one implements a different variant of the algorithm.
๐Ÿ“Š Sort Example (from motivation)
       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
       โ”‚  SortArray   โ”‚ โ—‡โ”€โ”€โ”€โ”€โ”€โ”€โ†’โ”‚ ยซinterfaceยป SortStrategy โ”‚
       โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”คsortStratโ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
       โ”‚ +sort()      โ”‚         โ”‚ +sort()              โ”‚
       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                          โ–ณ
                          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                  โ”‚ BubbleSortโ”‚  โ”‚ QuickSort  โ”‚  โ”‚ InsertionSortโ”‚
                  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
๐ŸชŸ Java AWT LayoutManager = Strategy!

ุงู„ู€ Java AWT ุจูŠุณุชุฎุฏู… Strategy ู„ู„ู€ Layout Managers. ุงู„ู€ Container = Context. ุงู„ู€ LayoutManager = Strategy.

Frame f = new Frame();
f.setLayout(new FlowLayout());    // strategy 1
// or:
f.setLayout(new GridLayout(2,3));  // strategy 2
// or:
f.setLayout(new BorderLayout());  // strategy 3

ุงู„ู€ Frame ู…ุง ูŠุนุฑูุด ุฅุฒุงูŠ ุจูŠุชู… ุงู„ู€ layout โ€” ู‡ูˆ ุจุณ ูŠุญูุธ reference ู„ู„ู€ LayoutManager. ูƒู„ strategy class ุจูŠู†ูู‘ุฐ layout algorithm ู…ุฎุชู„ู.

08

TextEditor Strategy โ€” Q3 Exam Solution โญ

ุงู„ู€ Question 3 ููŠ ุงู…ุชุญุงู†ุงุช Fall 2021-22 ูˆ Winter 2021. Practice these by heart.

๐Ÿ“œ Original Code (before Strategy)
TextEditor.java โ€” Bad design
public class TextEditor {
  private String text;

  public void formatText(int choice) {
    if (choice == 1) {
      text = text.toUpperCase();
    }
    else if (choice == 2) {
      text = text.toLowerCase();
    }
  }

  public void setText(String newText) { text = newText; }
  public String getText() { return text; }
}

public class Test {
  public static void main(String[] args) {
    TextEditor editor = new TextEditor();
    editor.setText("this Is My TeXt");
    editor.formatText(1);
    System.out.println(editor.getText());  // THIS IS MY TEXT
    editor.formatText(2);
    System.out.println(editor.getText());  // this is my text
  }
}
โ“ The 3 Parts of Question 3
  1. Part a (1 mark): What is the output of the code?
    Answer: THIS IS MY TEXT on line 1, this is my text on line 2.
  2. Part b (2 marks): How does adding a choice for formatting violate OCP and affect existing classes?
    Answer: Code should be open for extensions, closed for modifications. But adding a new formatter requires modifying the existing class (add new if). This violates OCP. Also, all clients using the class must be updated.
  3. Part c (5 marks for diagram + 7 marks for code): Apply Strategy Pattern. Draw UML + Write Java code.
๐Ÿ“ Solution โ€” UML Class Diagram (5 marks)
   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
   โ”‚  Test   โ”‚โ”€โ”€โ”€โ”€โ”€โ†’โ”€โ†’โ”‚  TextEditor   โ”‚ โ”€โ—‡โ”€โ”€โ”€โ”€โ†’โ”‚ ยซabstractยป TextFormattingStrategy โ”‚
   โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค         โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค        โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
   โ”‚  main() โ”‚         โ”‚ -text:String  โ”‚        โ”‚ +formatText(text:String):String โ”‚
   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜         โ”‚ -formatter    โ”‚        โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                       โ”‚ +setText()    โ”‚                       โ–ณ
                       โ”‚ +getText()    โ”‚                       โ”‚ extends
                       โ”‚ +setFormatter()โ”‚         โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                       โ”‚ +formatText() โ”‚         โ”‚                            โ”‚
                       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                          โ”‚ UpperCaseFormatterโ”‚  โ”‚ LowerCaseFormatterโ”‚
                                          โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค  โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
                                          โ”‚ +formatText(text):โ”‚  โ”‚ +formatText(text):โ”‚
                                          โ”‚   String         โ”‚  โ”‚   String         โ”‚
                                          โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ˜• Solution โ€” Java Code (7 marks)

1๏ธโƒฃ TextEditor (Context)

public class TextEditor {
  private String text;
  private TextFormattingStrategy formatter;  // 1 mark

  public void setFormatter(TextFormattingStrategy formatter) {
    this.formatter = formatter;  // 1 mark
  }

  public void setText(String newText) { text = newText; }
  public String getText() { return text; }

  public void formatText() {
    text = formatter.formatText(text);  // 1 mark
  }
}

2๏ธโƒฃ Abstract Strategy Class

abstract public class TextFormattingStrategy {
  abstract public String formatText(String text);
}

3๏ธโƒฃ Concrete Strategies

public class LowerCaseFormatter extends TextFormattingStrategy {
  public String formatText(String text) {
    return text.toLowerCase();
  }
}

public class UpperCaseFormatter extends TextFormattingStrategy {
  public String formatText(String text) {
    return text.toUpperCase();
  }
}

4๏ธโƒฃ Test Client

public class Test {
  public static void main(String[] args) {
    TextEditor editor = new TextEditor();
    editor.setText("this Is My TeXt");

    editor.setFormatter(new UpperCaseFormatter());  // 0.5
    editor.formatText();
    System.out.println(editor.getText());  // THIS IS MY TEXT

    editor.setFormatter(new LowerCaseFormatter());  // 0.5
    editor.formatText();
    System.out.println(editor.getText());  // this is my text
  }
}
๐Ÿ’ก Benefits achieved
  1. OCP satisfied โ€” add new formatter without touching TextEditor.
  2. Polymorphism โ€” TextEditor doesn't know which formatter is used.
  3. Open for extension โ€” create new ConcreteStrategy classes (e.g., TitleCaseFormatter).
๐ŸŽฏ

Exam Bank โ€” Lecture 12

8 ุฃุณุฆู„ุฉ ู…ู† ุงู„ู€ exams ุงู„ุญู‚ูŠู‚ูŠุฉ. Strategy, Observer, Template Method, MVC.

Question 1 Practice โ€” Strategy
A class has multiple algorithms selected via switch. Which design pattern would best refactor this?
A Observer
B Strategy
C Singleton
D Adapter
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: B โ€” Strategy Strategy pattern encapsulates each algorithm in its own class. ุงู„ู€ switch ุจูŠุชู… ุงุณุชุจุฏุงู„ู‡ ุจู€ polymorphism. ุฏู‡ classic refactor ุงู„ู€ Strategy.
Question 2 Fall 2021โ€“22 / Winter 2021 ยท Q1.17
A water company has a CRM system, billing system, and messaging system. When a customer is created in CRM, billing & messaging systems need to be notified and get a copy of customer data. Which design pattern suits this case?
A GoF pattern (any)
B Publish-Subscribe (Observer)
C Strategy
D MVC
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: B โ€” Publish-Subscribe (Observer) ุงู„ู€ CRM ูŠู†ุดุฑ event ("new customer"). Billing & Messaging ูŠุดุชุฑูƒูˆุง ูˆูŠุชู… notify ุนู†ุฏ ุงู„ุญุฏุซ. Each subscriber ูŠุญุตู„ ุนู„ู‰ copy. Classic Pub-Sub / Observer pattern.
A โ€” too generic. ยท C (Strategy) โ€” ู„ู„ู€ swap algorithms. ยท D (MVC) โ€” UI pattern.
Question 3 Fall 2021โ€“22 / Winter 2021 ยท Q1.18
In the MVC pattern shown with components @Observable (1), @EventListener (2), @Observer (3) โ€” what are classes 1, 2, and 3 in order?
A View, Controller, Model
B Model, View, Controller
C Model, Controller, View
D Controller, View, Model
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: C โ€” Model, Controller, View
  • ุงู„ู€ Model = @Observable (ุงู„ู€ source ู„ู„ู€ data changes)
  • ุงู„ู€ Controller = @EventListener (ูŠุณุชุฌูŠุจ ู„ู€ events)
  • ุงู„ู€ View = @Observer (ูŠุชู… notify ุนู†ุฏ changes)
Question 4 Winter 2025 ยท Q1.08
A class ReportBuilder has a buildReport() method that calls gatherData(), formatReport(), printReport() in order. formatReport() is abstract. SalesReport extends ReportBuilder overrides specific methods. Which pattern is this?
A Observer
B Strategy
C MVC
D Template Method
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: D โ€” Template Method Template Method = ุงู„ู€ base class defines a fixed algorithm (sequence) with some abstract steps. Subclasses override the abstract steps. ุงู„ู€ structure ู‡ู†ุง exactly that.
A (Observer) โ€” ู…ููŠุด notification mechanism. ยท B (Strategy) โ€” Strategy = composition (HAS-A); Template = inheritance (IS-A) with hooks. ยท C (MVC) โ€” ู…ุด UI pattern.
Question 5 Practice โ€” Strategy benefits
Which SOLID principle is most directly satisfied by Strategy Pattern?
A Open-Close Principle
B Liskov Substitution
C Interface Segregation
D Single Responsibility
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: A โ€” OCP Strategy = open for extension (add new strategy classes), closed for modification (Context class doesn't change). ุฏู‡ exact embodiment ู„ู„ู€ OCP.
Question 6 Practice โ€” Strategy structure
In Strategy Pattern, which class holds the reference to the current strategy?
A Strategy interface
B ConcreteStrategy
C Context
D Test/Client
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: C โ€” Context Context = the class ุงู„ู€ delegating the algorithm (e.g., TextEditor, SortArray). It HAS-A Strategy as a field, calls strategy.algorithm() in its operation.
Question 7 Practice โ€” Real-world Strategy
Which Java AWT/Swing component uses the Strategy Pattern internally?
A ActionListener
B Container with LayoutManager
C JComboBox
D JFrame
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: B โ€” Container with LayoutManager Container = Context. LayoutManager = Strategy interface. FlowLayout, GridLayout, BorderLayout = ConcreteStrategies. container.setLayout(new FlowLayout()) = swap strategy at runtime!
A (ActionListener) โ€” closer to Observer pattern (event listener).
Question 8 Practice โ€” GoF
Strategy belongs to which GoF category?
A Creational
B Structural
C Architectural
D Behavioral
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: D โ€” Behavioral Behavioral patterns deal with object interaction and responsibility distribution. Strategy + Observer + Template Method + Command + Iterator etc. ูƒู„ู‡ู… behavioral.
๐Ÿ“‹

Cheat Sheet

Design Patterns + Strategy complete reference.

๐Ÿ“š GoF Categories

Creational (5)
Abstract Factory ยท Builder ยท Factory Method ยท Prototype ยท Singleton
Structural (7)
Adapter ยท Bridge ยท Composite ยท Decorator ยท Faรงade ยท Flyweight ยท Proxy
Behavioral (11)
CoR ยท Command ยท Iterator ยท Mediator ยท Memento ยท Observer ยท State ยท Strategy ยท Template Method ยท Visitor ยท Interpreter

๐ŸŽฏ Strategy Pattern (Q3)

Category
Behavioral
Intent
Family of algorithms, encapsulated, interchangeable
Structure
Context + Strategy interface + ConcreteStrategies
SOLID applied
OCP + DIP
Trigger
if/else / switch chain for behavior

๐Ÿ”„ Pattern โ†’ Use Case

Strategy
Multiple algorithms (sort, format, layout)
Observer
Notify many objects of state change
Adapter
Make incompatible interfaces work together
Template Method
Fixed algorithm steps + customizable parts
Singleton
Ensure ONE instance only
MVC
Separate Model ยท View ยท Controller

๐Ÿ“ 4 Elements of Pattern

1. Name
Vocabulary handle
2. Problem
When to apply + context
3. Solution
Design + relationships
4. Consequences
Trade-offs & results

๐ŸชŸ Java GUI

Old
AWT (java.awt)
Standard
Swing (javax.swing) โ€” starts with J
Modern
JavaFX โ€” Stage, Scene, Node
Strategy in Java
setLayout(new FlowLayout())

โฐ Q3 Exam Strategy

1 mark
Read code output
2 marks
Explain OCP violation
5 marks
Draw UML (Context + abstract + 2 concretes)
7 marks
Java code (4 classes minimum)
Total Q3
15-24 marks
โšก

Rapid Revision

Flashcards ยท Mistakes ยท Doctor favorites.

3 GoF categoriesุŸ
tap
Creational ยท Structural ยท Behavioral
Strategy = ?
tap
Family of algorithms, interchangeable
Strategy structureุŸ
tap
Context + Strategy interface + ConcreteStrategies
Observer / Pub-Sub use caseุŸ
tap
Notify multiple systems of state change
Template Method vs StrategyุŸ
tap
Template = inheritance + hooks. Strategy = composition + swap
Java AWT example of StrategyุŸ
tap
setLayout() with FlowLayout/GridLayout/BorderLayout
MVC rolesุŸ
tap
Model ยท View ยท Controller
GoF book yearุŸ
tap
1995 (Gamma, Helm, Johnson, Vlissides)
Strategy โ†’ which SOLIDุŸ
tap
OCP + DIP

๐Ÿšจ Common Mistakes

1. Strategy vs Template MethodStrategy uses composition (Context HAS-A Strategy). Template Method uses inheritance (Subclass IS-A Base, overrides hooks).
2. Forgetting Test class in Q3 codeุงู„ู€ exam ุจูŠุฏูŠ 7 marks ู„ู„ู€ code. ู„ุงุฒู… ุงุฑุจุนุฉ classes: Context ยท Abstract Strategy ยท 2 Concrete Strategies ยท Test (which uses them).
3. Strategy as ObserverStrategy = swap behavior. Observer = notify changes. ู…ุฎุชู„ููŠู† ุจุงู„ูƒุงู…ู„.
4. ู„ูˆ UML ุจุฏูˆู† Concrete StrategiesUML ู„ู„ู€ Strategy ู„ุงุฒู… ุชุถู… 2+ concrete strategy classes โ€” ู…ุด ุจุณ Context + abstract.

โญ What Dr. El-Ramly Loves (Q3)

๐Ÿ”ฅ Q3 Pattern (every exam)
  1. "What is the output?" โ€” ู‚ุฑู‘ุงุก ุงู„ูƒูˆุฏ ูˆุญุฏุฏ output ุงู„ู€ println.
  2. "Explain OCP violation" โ€” code with if/else for behavior = OCP violation.
  3. "Draw UML" โ€” Context + abstract Strategy + 2 concrete strategies.
  4. "Write Java code" โ€” full implementation of 4 classes.
  5. ุงู„ุชุฑูƒูŠุฒ ุนู„ู‰ TextEditor formatText ุจุดูƒู„ ุฃุณุงุณูŠ.
  6. Winter 2023 Q3 was bigger: Observer + DIP + Adapter (24 marks total).
๐ŸŽฏ Final Tipุงุญูุธ TextEditor Strategy implementation by heart. ู„ูˆ ุฌุง ููŠ ุงู„ู€ exam ุจุฃูŠ ุดูƒู„ุŒ ุชู‚ุฏุฑ ุชูƒุชุจู‡ ููŠ 10 ุฏู‚ุงูŠู‚. ุงู„ู€ 15 mark ุฏูˆู„ guaranteed.