架構師訓練營 week3 總結
设计模式:使用设计模式优化排序工具包的设计
什麼是設計模式
每一種模式都描述了一種通用的解決方案
一種可重覆使用的解決方案
設計模式的四個部分
模式的名稱
待解問題
解決方案
結論
設計模式的分類
從功能分
Creational Pattens
從方式分
類模式
Simple Factory Pattern
from
to
# use simple_factory patten to extract “case when” to RuleConfigParserFactory.
RuleConfigSource => OOP
Factory Pattern
Simple Factory VS Factory
If the initialize part is easy, use “Simple Factory"
Singleton Pattern
Singleton
Reduce resource-consuming => performance requirement
Easy to control (only one instance) => feature requirement
Need to consider
Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.
Thread-safe?
Lazy loading?
Performance for getting instance
How to implement it?
Eager load
Lazy load
Lazy load but reuse
Static internal class
Hash
What problems?
Not OOP
Program to an interface, not an implementation
Hide the Dependency between classes
Not good to test
Because that is global, if someone updates it, it is not easy to find
Adapter Pattern
Adapter => allows objects with incompatible interfaces to collaborate.
Class adapter => inheritance
Object adapter => assemble
Some use cases:
Encapsulate flawed interface design
Unify multiple classes' interfaces
Replace 3rd-party’s interfaces
New/Old versions compatible
Adapter different data formats
Wrapper Patterns
Adapter: provide different interface, but Decorator and Proxy provide the same interface
Decorator: similar with Proxy, same interface, but strength original class’s functions
Proxy: similar with Decorator, same interface, do not strength function and but controlling access
Template Pattern
Template Pattern: defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.
Base Class define the structure
Sub Class implement the detail
Mainly solve these problems
Reuse
Expand
3 types of methods for Template Pattern
Abstract method => mandatory for subclass
Base method => subclass can override but not mandatory
Hook => for subclass
Strategy Pattern
Use to prevent long “if else” or “case"
Definition of strategy
Strategy interface, some ConcreteStrategy classes to implement
How to build
Use factory patten to encapsulate the detail
How to use
Decorator Pattern
Decorator class and original class inherit from the same base case, then we can have many decorator classes
Original function enhancement
Proxy patten: add functions which are non-related with the original class
Composite Pattern
Composite: Compose objects into tree structure to represent part-whole hierarchies.Composite lets client treat individual objects and compositions of objects uniformly.
將一組對象組織成樹狀結構,單個對象和組合對象都是樹中的節點,統一處理邏輯
利用樹狀結構,遞迴處理每個子樹
评论