C++ 有哪些經常用到的設計模式?
01-27
設計模式中真正被廣泛應用的有哪些?
標準庫中用到的設計模式有iterator,adapter.stack,queue,priority_queue用到了adapter模式,把底層容器的介面轉換為數據結構的介面。
單例。寫過消息隊列、線程池、日誌對象、配置文件對象。
那麼什麼時候該用單例,又該怎麼用呢?
stackoverflow上有人給出了不錯的總結,直接搬過來:
Use a Singleton if:
- If you need to have one and only one object of a type in system
Do not use a Singleton if:
- If you want to save memory
- If you want to try something new
- If you want to show off how much you know
- Because everyone else is doing it (See cargo cult programmer in wikipedia)
- In user interface widgets
- It is supposed to be a cache
- In strings
- In Sessions
- I can go all day long
How to create the best singleton:
- The smaller, the better. I am a minimalist
- Make sure it is thread safe
- Make sure it is never null
- Make sure it is created only once
- Lazy or system initialization? Up to your requirements
- Sometimes the OS or the JVM creates singletons for you (e.g. in Java every class definition is a singleton)
- Provide a destructor or somehow figure out how to dispose resources
- Use little memory
2.http://gameprogrammingpatterns.com/singleton.html
3.http://stackoverflow.com/questions/86582/singleton-how-should-it-be-used
(文中關於何時使用單例如何使用單例的英文總結來自這個鏈接)
4.http://www.cnblogs.com/loveis715/archive/2012/07/18/2598409.html
5.https://sourcemaking.com/design_patterns
(這個網站上有所有設計模式的C++實現)
type traits
observer
GUI-&>組合模式
數據結構遍歷-&>迭代器
消息機制-&>觀察者模式資源管理-&>單例模式singleton,最經常乾的事是把相關的全局變數包在一起factory,業務流程和測試流程構造不同的實例
Crtp
第一個必須是singleton,好懂好實現,還有composite, observer, iterator, object factory也很常用
推薦閱讀:
※如何用C實現C++類裡面的成員?
※socket拋出Cant assign requested address,問題所在以及解決方法?
※C++序列化json字元串對Unicode有哪些特殊處理?
※今天面試C++,機試面試官看完代碼說代碼結構混亂?
※C++primer中一個疑似錯誤?