A.创建型模式
- 抽象工厂(Abstract Factory)
DocumentBuilderFactory通过FactoryFinder实例化具体的Factory.
使用例子: DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse (new File("xxx.xml"));
javax.xml.transform.TransformerFactory
使用例子: StreamSource source = new StreamSource(...); StreamSource stylesource = new StreamSource(...); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(stylesource); StreamResult result = new StreamResult(System.out); transformer.transform(source, result)
The structure is almost the same as the previous two.
XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); XPathExpression expr = xpath.compile(XPATH_EXPRESSION_STRING); Object result = expr.evaluate(Object item, QName returnType);
2.生成器模式(Builder)
java.lang.StringBuilder#append()
java.lang.StringBuffer#append()
这里我们看到状态的转换操作都会返回原来的类型的对象,这样就可以构建生成链。
java.nio.ByteBuffer#put()
(CharBuffer
, ShortBuffer
, IntBuffer
, LongBuffer
, FloatBuffer
还有 DoubleBuffer
)
参见上例。
3.工厂方法(Factory method)
java.util.Calendar#getInstance()
工厂方法的构造方法就在所要生成的类型上。 这个抽象工厂有很大不同。
其它的可参见:
java.util.ResourceBundle#getBundle()
java.text.NumberFormat#getInstance()
java.nio.charset.Charset#forName()
java.net.URLStreamHandlerFactory#createURLStreamHandler(String)
4.原型模式(Prototye)
5.单例模式(Singleton)
java.lang.Runtime#getRuntime()
JDK 源码 阅读 - 2 - 设计模式 - 创建型模式
时间: 2024-10-08 13:31:58