Skip to content
CS-606 · Skill Development Lab/Quick Revision Short Notes

Skill Development Lab (CS-606) - Unit 4 Short Notes

How unit 4 is examined

This unit covers the second set of design patterns, usually the behavioural ones (how objects communicate and share responsibility), and no past question has been asked on it in the supplied papers.

Design Patterns - II

<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>

Definition. <mark>A design pattern is a proven, reusable solution to a commonly occurring problem in software design, described as a template that is adapted to the situation rather than finished code.</mark>

Diagram.

<figure class="ds-fig" style="margin:1.4rem 0;overflow-x:auto"><svg xmlns="http://www.w3.org/2000/svg" id="dsfig-u4-01" viewBox="0 0 880 194" width="880" height="194" role="img" aria-label="The three pattern families; Design Patterns - II is normally the behavioural family"><style>#dsfig-u4-01 .e{stroke:#454C5A;stroke-width:1.4;fill:none}#dsfig-u4-01 .e.hi{stroke:#2340B8;stroke-width:2.6}#dsfig-u4-01 .n{fill:#FFFFFF;stroke:#16181D;stroke-width:1.4}#dsfig-u4-01 .n.hi{fill:#E3E9FC;stroke:#2340B8;stroke-width:2.2}#dsfig-u4-01 .n.rb-b{fill:#16181D;stroke:#16181D}#dsfig-u4-01 .n.rb-r{fill:#BD3227;stroke:#BD3227}#dsfig-u4-01 text{font-family:"JetBrains Mono",ui-monospace,Menlo,Consolas,monospace;font-size:13px}#dsfig-u4-01 .t{fill:#16181D;font-weight:500}#dsfig-u4-01 .t.inv{fill:#FFFFFF;font-weight:700}#dsfig-u4-01 .kd{stroke:#16181D;stroke-width:1.2}#dsfig-u4-01 .dot{fill:#16181D}#dsfig-u4-01 .ann{fill:#2340B8;font-size:11px;font-weight:700}#dsfig-u4-01 .lbl{fill:#6F7787;font-family:system-ui,-apple-system,sans-serif;font-size:12px;font-weight:700}#dsfig-u4-01 .ptr{fill:#2340B8;font-size:12px;font-weight:700}#dsfig-u4-01 .ah{fill:#454C5A}#dsfig-u4-01 .ah.hi{fill:#2340B8}#dsfig-u4-01 .wl rect{fill:#FFFFFF;stroke:#DCE0E7}#dsfig-u4-01 .wl .t{font-size:12px;font-weight:700}#dsfig-u4-01 .wl.hi rect{fill:#2340B8;stroke:#2340B8}#dsfig-u4-01 .wl.hi .t{fill:#FFFFFF}html.dark #dsfig-u4-01 .e{stroke:#B1B7C3}html.dark #dsfig-u4-01 .e.hi{stroke:#8FA3FF}html.dark #dsfig-u4-01 .n{fill:#161920;stroke:#E6E8ED}html.dark #dsfig-u4-01 .n.hi{fill:#1E2748;stroke:#8FA3FF}html.dark #dsfig-u4-01 .n.rb-b{fill:#E6E8ED;stroke:#E6E8ED}html.dark #dsfig-u4-01 .n.rb-r{fill:#FF7E71;stroke:#FF7E71}html.dark #dsfig-u4-01 .t{fill:#E6E8ED}html.dark #dsfig-u4-01 .t.inv{fill:#0F1115}html.dark #dsfig-u4-01 .kd{stroke:#E6E8ED}html.dark #dsfig-u4-01 .dot{fill:#E6E8ED}html.dark #dsfig-u4-01 .ann{fill:#8FA3FF}html.dark #dsfig-u4-01 .lbl{fill:#858D9C}html.dark #dsfig-u4-01 .ptr{fill:#8FA3FF}html.dark #dsfig-u4-01 .ah{fill:#B1B7C3}html.dark #dsfig-u4-01 .ah.hi{fill:#8FA3FF}html.dark #dsfig-u4-01 .wl rect{fill:#161920;stroke:#2A2E37}html.dark #dsfig-u4-01 .wl.hi rect{fill:#8FA3FF;stroke:#8FA3FF}html.dark #dsfig-u4-01 .wl.hi .t{fill:#0F1115}</style><defs><marker id="ah2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah" d="M0,1 L9,5 L0,9 z"/></marker><marker id="ahh2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah hi" d="M0,1 L9,5 L0,9 z"/></marker></defs><line class="e" x1="295.8" y1="37" x2="63" y2="101"/><line class="e" x1="295.8" y1="37" x2="177" y2="101"/><line class="e" x1="295.8" y1="37" x2="528.5" y2="101"/><line class="e" x1="528.5" y1="101" x2="283.5" y2="165"/><line class="e" x1="528.5" y1="101" x2="382.5" y2="165"/><line class="e" x1="528.5" y1="101" x2="477.5" y2="165"/><line class="e" x1="528.5" y1="101" x2="572.5" y2="165"/><line class="e" x1="528.5" y1="101" x2="659.5" y2="165"/><line class="e" x1="528.5" y1="101" x2="773.5" y2="165"/><rect class="n" x="227.3" y="22" width="137" height="30" rx="8"/><text class="t" x="295.8" y="37" dy=".35em" text-anchor="middle">Design patterns</text><rect class="n" x="14" y="86" width="98" height="30" rx="8"/><text class="t" x="63" y="101" dy=".35em" text-anchor="middle">Creational</text><rect class="n" x="128" y="86" width="98" height="30" rx="8"/><text class="t" x="177" y="101" dy=".35em" text-anchor="middle">Structural</text><rect class="n" x="475.5" y="86" width="106" height="30" rx="8"/><text class="t" x="528.5" y="101" dy=".35em" text-anchor="middle">Behavioural</text><rect class="n" x="242" y="150" width="83" height="30" rx="8"/><text class="t" x="283.5" y="165" dy=".35em" text-anchor="middle">Observer</text><rect class="n" x="341" y="150" width="83" height="30" rx="8"/><text class="t" x="382.5" y="165" dy=".35em" text-anchor="middle">Strategy</text><rect class="n" x="440" y="150" width="75" height="30" rx="8"/><text class="t" x="477.5" y="165" dy=".35em" text-anchor="middle">Command</text><rect class="n" x="531" y="150" width="83" height="30" rx="8"/><text class="t" x="572.5" y="165" dy=".35em" text-anchor="middle">Iterator</text><rect class="n" x="630" y="150" width="59" height="30" rx="8"/><text class="t" x="659.5" y="165" dy=".35em" text-anchor="middle">State</text><rect class="n" x="705" y="150" width="137" height="30" rx="8"/><text class="t" x="773.5" y="165" dy=".35em" text-anchor="middle">Template Method</text></svg><figcaption style="font-size:.82em;opacity:.72;margin-top:.45rem">The three pattern families; Design Patterns - II is normally the behavioural family</figcaption></figure>

Key points.

  1. Design Patterns - II usually covers behavioural patterns, which describe how objects interact and how responsibility is divided among them, while Design Patterns - I covers creational and structural patterns.
  2. Observer defines a one-to-many dependency, so that when one object (the subject) changes state all its dependents (observers) are notified and updated automatically, as in event listeners and publish-subscribe.
  3. Strategy puts a family of algorithms behind one common interface and makes them interchangeable, so the algorithm can be chosen or changed at run time without changing the client, for example different sorting or payment methods.
  4. Command wraps a request as an object, which lets the system queue requests, log them, pass them around and support undo and redo.
  5. Iterator gives sequential access to the elements of a collection without exposing its internal structure, so the same loop works for a list, a tree or a set.
  6. State lets an object change its behaviour when its internal state changes, so it appears to change its class, for example a document that is draft, moderated or published.
  7. Template Method fixes the skeleton of an algorithm in a base class and leaves some steps to subclasses, so the order stays the same while the steps vary.
  8. Every pattern is described by its name, problem, solution and consequences, and the benefits are reuse of proven design, a shared vocabulary for developers and looser coupling between classes.

Comparison.

Pattern Problem it solves Core idea Everyday example
Observer Many objects must react to one change Subject notifies registered observers Notifications, event listeners
Strategy Several ways to do one task Interchangeable algorithm objects Payment method, sort order
Command Requests must be queued or undone Request becomes an object Undo in an editor
Iterator Traverse without exposing structure Separate traversal object for-each loop
State Behaviour depends on state Delegate to a state object Order status
Template Method Same steps, different details Base class fixes the order Framework hooks

Example. In a weather app the WeatherData object is the subject and the phone display, the web display and the alert service are observers. When the temperature changes, WeatherData calls update() on each registered observer, and a new display can be added by registering it, without editing WeatherData.

More behavioural patterns. 9. Chain of Responsibility passes a request along a chain of handlers until one of them handles it, as in a help desk that escalates from level 1 to level 3 support. 10. Mediator puts the communication between many objects into one mediator object, so the objects do not refer to each other directly, as an air traffic controller does for aircraft. 11. Memento saves an object's internal state in a separate object so that it can be restored later without breaking encapsulation, which is how a checkpoint or an undo history works. 12. Visitor moves a new operation out of the element classes into a visitor object, so an operation can be added to a class hierarchy without editing the classes.

Steps for Observer.

Step 1: The subject keeps a list of observers and offers attach() and detach().
Step 2: Each observer implements a common update() method.
Step 3: An observer calls attach() to register with the subject.
Step 4: When the subject's state changes it calls notify().
Step 5: notify() calls update() on every registered observer.
Step 6: Each observer reads the new state and refreshes itself.

Code.

class Subject:
    def __init__(self): self.obs, self.state = [], 0
    def attach(self, o): self.obs.append(o)
    def set_state(self, s):
        self.state = s
        for o in self.obs: o.update(s)
class Display:
    def update(self, s): print("temp is", s)
sub = Subject(); sub.attach(Display()); sub.set_state(30)  # temp is 30

Benefits and cost. Patterns improve reuse, readability and maintenance and give developers a common vocabulary, but applying a pattern where a simple design would do adds needless classes and complexity.

Strategy in practice.

class Cash:
    def pay(self, amt): return f"cash {amt}"
class Card:
    def pay(self, amt): return f"card {amt}"
class Cart:
    def __init__(self, method): self.method = method
    def checkout(self, amt): return self.method.pay(amt)
print(Cart(Card()).checkout(500))  # card 500

The Cart never changes when a new payment class is added, which is the open-closed principle: open for extension, closed for modification.

Command in practice. An editor stores each action as a command object with execute() and undo() methods and pushes it on a stack. Undo pops the last command and calls its undo(), and redo calls execute() again, so the editor needs no knowledge of what each action does.

Pattern description. A full description lists the name, intent, problem, solution (participants and their collaboration), consequences and known uses, and a written answer should follow this order.

Choosing a pattern. Pick Observer when many objects depend on one, Strategy when an algorithm must be swappable, Command when a request must be stored or undone, Iterator when a collection must be traversed safely, and State when behaviour depends on a mode. Two patterns are often combined, for example a Command history that notifies its views through Observer.

Iterator in practice. A collection returns an iterator with hasNext() and next() methods, and the client loops with these two calls only, so the underlying list, tree or set can be replaced without changing the loop.

Answer frame. Open with the definition of a design pattern and name the family; draw the pattern's class diagram with subject and observer boxes and the notify arrow; develop the intent, participants, working, example and benefits in that order; close with one line on the loose coupling that the pattern gives.

Pitfall: Do not mix up families: Observer, Strategy and Command are behavioural, not creational or structural.

Last-minute revision

  • A design pattern is a reusable solution template to a recurring design problem, not ready-made code.
  • The three families are creational, structural and behavioural.
  • Design Patterns - II is normally the behavioural group, which concerns object interaction.
  • Observer is one-to-many notification on a state change.
  • Strategy swaps algorithms at run time through a common interface.
  • Command turns a request into an object so it can be queued, logged or undone.
  • Iterator gives sequential access without exposing the collection's structure.
  • State changes an object's behaviour when its internal state changes.
  • Template Method fixes the algorithm's order and lets subclasses supply the steps.
  • A pattern description has a name, problem, solution and consequences.

Memory hooks

  • Observer means subscribe and get told.
  • Strategy means swap the algorithm.
  • Command means request as an object, so undo is possible.
  • Behavioural patterns describe who talks to whom.
  • Template Method means the parent decides the order and the child fills the steps.

Coverage checklist

  • Design Patterns - II: definition, pattern families, Observer, Strategy, Command, Iterator, State, Template Method, comparison table (no past questions).
Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in