天天看點

設計模式學習之路-設計模式什麼設計模式的六大原則設計模式的分類實際使用場景

設計模式是什麼?我能想到的是「套路」,或者說是「最佳實踐」。要寫出「好代碼」,我們需要遵循一些「最佳實踐」,就好像我們要培養優秀的個人品行,需要遵循一些「美德」。

以下是美國國父富蘭克林給自己列的「美德」清單:

節制:食不可飽,衣不過量。

慎言:隻講對人對己有益之言,不說無聊瑣碎之話。

條理:讓擁有的每件東西都各有其位,讓要做的每件事都各有其時。

堅毅:一旦決定做一件事,就馬上義無反顧的去做。

節儉:将錢用在于人于己有益的事情上,杜絕浪費。

勤奮:不耽誤任何時間,總是在幹有用的事情,終止不必要的行為。

真誠:不采用任何有害的欺騙行為,想問題和說話都要公平公正。

正直:絕不做損人利己之事。

适度:避免極端,避免别人對你産生怨恨。

清潔:決不允許身體、衣服和居所不潔。

心靜:不被瑣碎之事,尋常之事,和不可避免之事萦繞。

貞潔:不過度行房事,也不因男女關系損害和他人的關系。

謙卑:以耶稣和蘇格拉底為楷模。

為什麼列這麼多美德?富蘭克林的邏輯是把美德分的細一些,每個美德隻包含一個簡單、清晰的外延,這樣就更容易做到了。

這麼多美德記都記不過來,怎樣才能做到?富蘭克林的方案是一周隻注重培養其中一個美德,這樣13周就是一個周期,一年可以循環4次。

以上的13條美德和2條富蘭克林的實踐,就是富蘭克林培養優秀個人品行的「設計模式」吧?

回到設計模式,設計模式中也有一些「美德」,我們簡稱它們為六大設計原則。

單一職責原則 single responsibility principle

定義:一個類應該隻有一個發生變化的原因。

there should never be more than one reason for a class to change.

開閉原則 open closed principle

定義:軟體實體(類、子產品、函數等)應該對擴充開放,對修改關閉。

software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

裡氏替換原則 liskov substitution principle

定義:如果對每一個類型為s的對象o1,都有類型為t的對象o2,使得以t定義的所有程式p在所在的對象o1都代換為o2時,程式p的行為沒有發生變化,那麼類型s是類型t的子類型。

if for each object o1 of type s there is an object o2 of type t such that for all programs p defined in terms of t,the behavior of p is unchanged when o1 is substituted for o2 then s is a subtype of t.

迪米特法則 law of demeter

定義:一個對象應該對其他對象有最少的了解。

only talk to your immediate friends.

接口隔離原則 interface segregation principle

定義:用戶端不應該依賴它不需要的接口。

clients should not be forced to depend upon interfaces that they don’t use.

依賴倒置原則 dependence inversion principle

定義:高層子產品不應該依賴低層子產品,二者都應該依賴其抽象;抽象不應該依賴細節;細節應該依賴抽象。

high level modules should not depend upon low level modules.both should depend upon abstractions.abstractions should not depend upon details.details should depend upon abstractions.

建立型模式

簡單工廠模式 simple factory pattern

工廠方法模式 factory method pattern

抽象工廠模式 abstract factory

建造者模式

單例模式

結構型模式

設配器模式

橋接模式

裝飾模式

外觀模式

享元模式

代理模式

行為型模式

指令模式

中介者模式

觀察者模式

狀态模式

政策模式

spring核心容器的主要元件是beanfactory,它是工廠模式的實作。

參考連結

<a href="http://design-patterns.readthedocs.io/zh_cn/latest/creational_patterns/simple_factory.html">http://design-patterns.readthedocs.io/zh_cn/latest/creational_patterns/simple_factory.html</a>

<a href="https://yq.aliyun.com/articles/109934">https://yq.aliyun.com/articles/109934</a>