23個經典JDK設計模式
Structural(結構模式)
Adapter:
把一個接口或是類變成另外一種。
o ● java.util.Arrays#asList()
o ● javax.swing.JTable(TableModel)
o ● java.io.InputStreamReader(InputStream)
o ● java.io.OutputStreamWriter(OutputStream)
o ● javax.xml.bind.annotation.adapters.XmlAdapter#marshal()
o ● javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal()
Bridge:
把抽象和實現解藕,于是接口和實現可在完全獨立開來。
o ● AWT (提供了抽象層映射于實際的操作系統)
o ● JDBC
Composite:
讓使用者把單獨的對象和組合對象混用。
o ● javax.swing.JComponent#add(Component)
o ● java.awt.Container#add(Component)
o ● java.util.Map#putAll(Map)
o ● java.util.List#addAll(Collection)
o ● java.util.Set#addAll(Collection)
Decorator:
為一個對象動態的加上一系列的動作,而不需要因為這些動作的不同而產生大量的繼承類。這個模式在JDK中幾乎無處不在,所以,下面的列表只是一些典型的。
o ● java.io.BufferedInputStream(InputStream)
o ● java.io.DataInputStream(InputStream)
o ● java.io.BufferedOutputStream(OutputStream)
o ● java.util.zip.ZipOutputStream(OutputStream)
o ● java.util.Collections#checked[List|Map|Set|SortedSet|SortedMap]()
Facade:
用一個簡單的接口包狀一組組件,接口,抽象或是子系統。
o ● java.lang.Class
o ● javax.faces.webapp.FacesServlet
Flyweight:
有效率地存儲大量的小的對象。
o ● java.lang.Integer#valueOf(int)
o ● java.lang.Boolean#valueOf(boolean)
o ● java.lang.Byte#valueOf(byte)
o ● java.lang.Character#valueOf(char)
Proxy:
用一個簡單的對象來代替一個復雜的對象。
o ● java.lang.reflect.Proxy
o ● RMI
Creational(創建模式)
Abstract factory:
創建一組有關聯的對象實例。這個模式在JDK中也是相當的常見,還有很多的framework例如Spring。我們很容易找到這樣的實例。
o ● java.util.Calendar#getInstance()
o ● java.util.Arrays#asList()
o ● java.util.ResourceBundle#getBundle()
o ● java.sql.DriverManager#getConnection()
o ● java.sql.Connection#createStatement()
o ● java.sql.Statement#executeQuery()
o ● java.text.NumberFormat#getInstance()
o ● javax.xml.transform.TransformerFactory#newInstance()
Builder:
主要用來簡化一個復雜的對象的創建。這個模式也可以用來實現一個 Fluent Interface。
o ● java.lang.StringBuilder#append()
o ● java.lang.StringBuffer#append()
o ● java.sql.PreparedStatement
o ● javax.swing.GroupLayout.Group#addComponent()
Factory:
簡單來說,按照需求返回一個類型的實例。
o ● java.lang.Proxy#newProxyInstance()
o ● java.lang.Object#toString()
o ● java.lang.Class#newInstance()
o ● java.lang.reflect.Array#newInstance()
o ● java.lang.reflect.Constructor#newInstance()
o ● java.lang.Boolean#valueOf(String)
o ● java.lang.Class#forName()