# OOAD Lab 14 (05/25)
###### tags: `OOAD`
---
[TOC]
---
## 14. Design Pattern 1
- **Patterns**:
- *What’s New Here is that Nothing is New Here*
- Patterns are about what works
- Patterns give us **a way to talk about what works**
- Patterns **distill experience**
- Patterns give us **a pithy design vocabulary**
- **Alexander on Patterns**:
- *Patterns in solutions come from patterns in problems.*
- *Patterns in solutions come from patterns in problems.*
- --- **Christopher Alexander -- A Pattern Language**
- **Design Patterns**:
- **過去,在實做各種各類的軟體過程中,許多人累積了寶貴的物件導向分析經驗。經過蒐集整理,這些寶貴的繼承架構,class diagram,物件互動架構等等,被蒐集成所謂的 design patterns。**
- Design pattern 也是**一種 reuse**,但不全然是 code reuse
- **Landmark book**:
- *Design Patterns: Elements of Reusable Object-Oriented Software*
- Author: Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (**The Gang of Four (GoF)**)
- Addison Wesley, 1995
- **Practice of Design Pattern**:
- In order to **achieve flexibility**, design patterns usually introduce **additional levels of indirection**, which in some cases may complicate the resulting designs and hurt application performance.
- Design patterns provide **general solutions**, **documented** in a format that does not require specifics tied to a particular problem.
- **Criticism of Design Pattern**:
- **Targets the wrong problem**
- ---> Find **PROBLEMS**
- ---> Need to **EXTEND instantly?**
- ---> Find **RIGHT and NECESSARY patterns**
- **Leads to inefficient solutions**
- **Increasing complexity**
- ---> Rule of **KISS**: *keep it simple and stupid*
- Design pattern make code **obscure and difficult to understand and to be extended**
- ---> ***"The OVERUSE is worst than NO USE it at all“***
- **Design Patterns in REAL WORLD**:
> Welcome to the real world
- As a **programmer**:
- You have **deadline**
- you have so many **features to catch on**
- You have so many **bugs to fix**
- **acceptable, usable > best, optimal**
- The real world is **dirty**:
- It is **impractical** to build a pure, perfect, optimal software in practice.
- In human history, **software evolve and advance gradually**.
- **every thing has a price (cost)**
- **Suggestion to Design Pattern**:
- Unless it is clear that a design pattern is necessary, otherwise, focus on solving the problem itself.
- Discover the problems of your implementation and its extension and future change
- See through the nature of your problem and find a design pattern to address it.
- - **GoF Design Patterns**:
- **Creational** patterns:
- Abstract Factory
- Builder
- **Factory Method**
- Prototype
- **Singleton**
- **Structural** patterns:
- Adapter
- Bridge
- **Composite**
- Decorator
- Facade
- Flyweight
- **Proxy**
- **Behavioral** Patterns:
- Chain of Responsibility
- Command
- Interpreter
- **Iterator**
- Mediator
- Memento
- **Observer**
- State
- Strategy
- **Template Method**
- **Visitor**
- **The Big Five**:
- Composite
- Proxy
- Strategy
- Observer
- Visitor
- **Composite**:
- 在圖形編輯器這種圖形化應用程式裡,常會用小零件拼出複雜的圖形,也會將幾個小零件結合成較大的群組物件。這個群組物件又可以當成零件來拼出更大的圖形。欲達此目的,直覺能想到的就是採用下面的 class diagram 繼承架構,其中group 是一個所謂的容器物件。
- **Example**:

- 我們所碰到的問題是,我們的程式碼要去判斷一個物件到底是基底物件還是 group 物件
- **不得不寫 `instanceof`**
- 一般繼承的規則都告訴我們,特異化的行為應該留在 sub class 就好。
- **---> Percolating up**:

- **Put `add()`, `remove()` in the parent class**
- **Singleton**:
> **The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it**
- **The need for singleton**:
- **Global variable are EVIL**
- **Why Global Variables Should Be Avoided When Unnecessary!**:
- **Non-locality**: 總體變數可以被任何地方的程式碼讀寫是難以理解跟除錯的
- **No Access Control or Constraint Checking**: 沒有存取控制以及限制查驗
- **Implicit coupling**: 隱晦的耦合
- **Concurrency issues**: 破壞並型與多執行續 thread-safe
- **Namespace pollution**: 名稱重疊汙染
- **Memory allocation issues**: 記憶體配置問題
- **Testing and Confinement**: 測試難題
- **Stupid way**:
- **Parameters**: In order to let other classes being able to access the unique object, we **pass ux all around**
- **Control Class**: Make the variable to be **static** so that it has only one instance which **comes with class not object**
- you do not new an object from a control class
- We always want ***an object to be created only when they are needed***
- **Pattern**:
```java
public class X {
private static X uniqueInstance;
private X() { }
public static X getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
```
- No public constructor to allow any program to “new” the object
- The new object is created in the getInstance()
- The variable inside the singleton is declared as static
- **Multi-thread-Safe**
```java
public class X {
private volatile static X uniqueInstance;
private X() { }
public static X getInstance() {
if (uniqueInstance == null) {
synchronized (X.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
```
- **Proxy**:
- 我們想要延緩一個物件的建立與初始化,原因是物件的建立與初始化需要速度與記憶體等等代價
- 我們希望當物件真正需要的時候才進行建立與初始化(on demand)
- 例如一份文件中的許多影像物件
- 但是這個延緩的過程應該物件自行處理掉,例如讀檔的程式碼不需要處理這些細節
- **Strategy**:
> **The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable.**
> **Strategy lets the algorithm vary independently from clients that use it.**
- **Use many "---able" interfaces ---> duplicated code ---> not code reuse**
- **Design Principle**:
- **Encapsulate** what varies
- **Program to an interface**, not an implementation
- polymorphism
- **Favor composition over inheritance**
- 

- The magic – you can have a duck whose **behavior can change in runtime**
- **flexibility**