Introduction to Design Patterns
ุงูู pattern = recurring solution ูู common problem ูู specific context.
- 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
ุชุจุฏุฃ ุจูุชุงุจุฉ 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 */ }
}
}
- Violates OCP โ for any new algorithm, you modify the class.
- Every change affects all clients that use it.
- What about future algorithms you don't know yet? You'll keep editing.
GoF โ 23 Design Patterns
ุชููุณู ูู 3 categories.
๐๏ธ Creational (5)
About object creation
- Abstract Factory
- Builder
- Factory Method
- Prototype
- Singleton โญ
๐๏ธ Structural (7)
About composition
- Adapter โญ (Q3 Winter 2023)
- Bridge
- Composite
- Decorator
- Faรงade
- Flyweight
- Proxy
๐ญ Behavioral (11)
About interaction
- Chain of Responsibility
- Command
- Interpreter
- Iterator
- Mediator
- Memento
- Observer โญ
- State
- Strategy โญโญโญ
- Template Method โญ
- Visitor
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.
Java GUI โ Swing & AWT
ุงูู Java libraries ููู GUI. ุงูู AWT ูู ุงูุฃุณุงุณุ ุงูู Swing ุจูุฑุซ ู ููุง.
- AWT (java.awt) โ old, OS-dependent rendering.
- Swing (javax.swing) โ new, classes start with
J(e.g.,JFrame,JPanel,JButton).
Sample Java GUI Composition
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);
}
}
ุงูู AWT/Swing components ุจุชูุดุฑ events. ุงูู EventListeners ุจุชุดุชุฑู ูููุง.
| Component | Event | Listener |
|---|---|---|
| JButton | ActionEvent | ActionListener |
| JComponent | MouseEvent | MouseListener |
| JComponent | KeyEvent | KeyListener |
// Adding listener with anonymous inner class
JButton again = new JButton("New game");
again.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame();
}
});
JavaFX โ Modern UI
Swing ูู ุงูู Legacy. JavaFX ูู ุงูู Modern Industry Standard.
| Feature | Swing (Legacy) | JavaFX (Modern) |
|---|---|---|
| Top-Level Container | JFrame | Stage |
| Content | JPanel / ContentPane | Scene |
| Component Base | JComponent | Node |
| Hierarchy | Flat: FrameโPanelโComp | Scene Graph: StageโSceneโRootโNodes |
| Layout | setLayout() | setRoot(newParent) |
| Styling | Java code | CSS |
| Graphics Engine | CPU (software) | GPU accelerated |
| Layout Strategy | FlowLayout, GridLayout, BorderLayout | HBox, VBox, GridPane, StackPane |
| Visual Design | Code only | FXML + Scene Builder |
| Multimedia | Limited | 3D, Video, Audio, WebKit built-in |
| Events | Anonymous inner classes | Lambda expressions |
Strategy Pattern โญโญโญ
ุงูู Pattern ุงูุฃูู ูู ุงูู course. Q3 ูู ูู final fingerprint exam.
๐ฏ 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.
- 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.
if/else chain ุฃู switch ุจูุฎุชุงุฑ between behaviors โ ููุฑ ูู Strategy.Strategy Pattern โ UML Structure
3 elements: Context ยท Strategy interface ยท Concrete Strategies.
โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 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.
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ
โ SortArray โ โโโโโโโโโ ยซinterfaceยป SortStrategy โ
โโโโโโโโโโโโโโโโคsortStratโโโโโโโโโโโโโโโโโโโโโโโโค
โ +sort() โ โ +sort() โ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ
โณ
โโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
โ BubbleSortโ โ QuickSort โ โ InsertionSortโ
โโโโโโโโโโโโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ
ุงูู 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 ู ุฎุชูู.
TextEditor Strategy โ Q3 Exam Solution โญ
ุงูู Question 3 ูู ุงู ุชุญุงูุงุช Fall 2021-22 ู Winter 2021. Practice these by heart.
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
}
}
- Part a (1 mark): What is the output of the code?
Answer:THIS IS MY TEXTon line 1,this is my texton line 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. - Part c (5 marks for diagram + 7 marks for code): Apply Strategy Pattern. Draw UML + Write Java code.
โโโโโโโโโโโ โโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 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 โ
โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ
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
}
}
- OCP satisfied โ add new formatter without touching TextEditor.
- Polymorphism โ TextEditor doesn't know which formatter is used.
- Open for extension โ create new ConcreteStrategy classes (e.g., TitleCaseFormatter).
Exam Bank โ Lecture 12
8 ุฃุณุฆูุฉ ู ู ุงูู exams ุงูุญููููุฉ. Strategy, Observer, Template Method, MVC.
switch. Which design pattern would best refactor this?@Observable (1), @EventListener (2), @Observer (3) โ what are classes 1, 2, and 3 in order?- ุงูู Model =
@Observable(ุงูู source ููู data changes) - ุงูู Controller =
@EventListener(ูุณุชุฌูุจ ูู events) - ุงูู View =
@Observer(ูุชู notify ุนูุฏ changes)
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?container.setLayout(new FlowLayout()) = swap strategy at runtime!
Cheat Sheet
Design Patterns + Strategy complete reference.
๐ GoF Categories
๐ฏ Strategy Pattern (Q3)
๐ Pattern โ Use Case
๐ 4 Elements of Pattern
๐ช Java GUI
โฐ Q3 Exam Strategy
Rapid Revision
Flashcards ยท Mistakes ยท Doctor favorites.
๐จ Common Mistakes
โญ What Dr. El-Ramly Loves (Q3)
- "What is the output?" โ ูุฑูุงุก ุงูููุฏ ูุญุฏุฏ output ุงูู println.
- "Explain OCP violation" โ code with if/else for behavior = OCP violation.
- "Draw UML" โ Context + abstract Strategy + 2 concrete strategies.
- "Write Java code" โ full implementation of 4 classes.
- ุงูุชุฑููุฒ ุนูู TextEditor formatText ุจุดูู ุฃุณุงุณู.
- Winter 2023 Q3 was bigger: Observer + DIP + Adapter (24 marks total).