This series of blog is his collection of articles collected in the learning process of design patterns, see the other articles in design mode Portal
Builders Model Description
The builder pattern is a creational design patterns, this model has a good encapsulation. Use the builder pattern can effectively change the package, in a scene using the builder pattern, the general product category and builders category is relatively stable, and therefore, the main business logic is encapsulated in the director category for the whole can achieve more good stability.
In the builder mode, the client does not have to know the details of the internal composition of the product, the product itself and the process of creating the product decoupled so that the same creation process can create different product objects.
You can more finely control the product creation process. The step of creating the complex decomposition products in different ways, so that the creation of clearer and more easy to use program to control the creation process.
Secondly, the builder pattern can easily be extended. If there are new needs, by implementing a new builder to complete the class, it has basically adopted prior to the test code without modification, and therefore no risk of the introduction of the original function. In line with the principle of opening and closing.
The builder pattern typically includes the following roles
Abstract builder class (builder): for creating product objects and abstract interface is specified individual components
Specific construction class (concreteBuilder): implement the interface builder, rewriting method of constructing a different representation
Product category (product): concrete products
Class conductor (director): Construction of a builder interface objects using
JDK in the builder pattern --StringBuilder
StringBuilder
Class is the embodiment of the builder pattern typical of the JDK. I look at the class diagram for this class:
We look at the situation corresponds to each role based on the map:
StringBuilder: the role of commander, holding the specific reference to the builder, because the StringBuilder inherited AbstractStringBuilder, StringBuilder here as a reference by super specific builders.
AbstractStringBuilder: concrete builder, which implements the append (Character c) method appendable interface.
Appendable: abstract builder, create objects defined interfaces.
String: product role.
In addition, StringBuffer also use the builder pattern. The only difference is that StringBuffer using synchronized to ensure thread safety, but StringBuilder is not thread safe.
In fact, the builder pattern in our usual development is reflected more like StringBuilder.append
this chained calls. StringBuilder is where the role of the commander, append method is the process of creating product details, when after we've created products can call toString method to generate specific products. For example, the following code
String str = new StringBuilder().append()
.append()
.toString();
There are many such similar code, such as
Header header = new HeaderBuilder()
.setClientId(SOAHeader.SOAP_CLIENT_ID)
.setCorrelationId(SOAHeader.SOAP_CORRELATION_ID)
.buildHeader();
In normal development, if we see a similar code above, you may use the builder pattern. We always pay attention to such a code to see why the author is designed such systems, to enhance our code very helpful. This is my finishing summarize common development framework design patterns intention.
Spring in the builder pattern
Spring Java developers is the most commonly used development framework. Some people say that Spring is the feast of the source code design patterns. Spring look at the source code is a good way to learn a design pattern.
In the Spring framework, often related to the builder pattern are:
- UriComponentsBuilder
- BeanDefinitionBuilder
In which BeanDefinitionBuilder
the lower levels, we usually do not will be used. We here UriComponentsBuilder
to tell the builder pattern Spring.
The following code, we in Spring restTemplate Tool Calling remote interface. Before calling the need to build the URL parameters. Here it is used UriComponentsBuilder
to build.
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl("127.0.0.1:8080").
path("/test").build(true);
URI uri = uriComponents.toUri();
RequestEntity<JSONObject> requestEntity = RequestEntity.post(uri).
//添加cookie(这边有个问题,假如我们要设置cookie的生命周期,作用域等参数我们要怎么操作)
header(HttpHeaders.COOKIE,"key1=value1").
//添加header
header(("MyRequestHeader", "MyValue")
accept(MediaType.APPLICATION_JSON).
contentType(MediaType.APPLICATION_JSON).
body(requestParam);
ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(requestEntity,JSONObject.class);
//响应结果
JSONObject responseEntityBody = responseEntity.getBody();
Spring has a lot of design patterns to be under careful attention when we usually use. I believe there will certainly be harvested.
MyBatis in the builder pattern
MyBatis most classic model builder definitely get SqlSessionFactory process.
Here is the typical usage of acquired SqlSessionFactory.
CopyClassPathResource resource = new ClassPathResource("mybatis-config.xml");
InputStream inputStream = resource.getInputStream();
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
Through the above code is found, create SqlSessionFactory code SqlSessionFactoryBuilder in, go check it out:
Copy//整个过程就是将配置文件解析成Configration对象,然后创建SqlSessionFactory的过程
//Configuration是SqlSessionFactory的一个内部属性
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
Code is relatively simple, not detailed analysis. Here is the condemnation, listed under each role.
- SqlSessionFactoryBuilder: the role of commander
- BaseBuilder:抽象Builder
- XMLConfigBuilder: Specific Builder
- SqlSessionFactory: the product needs to be created
Sentiment
Study design patterns learning light does not work, because this thing is more abstract. You have to look at the project in conjunction with the specific framework in order to have deeper insights.
Usually if you have spare time to do it yourself, use design patterns to write some small frame. There is more to see the source code for those mainstream open-source framework, the code is reflected in both design patterns. Combined with theoretical knowledge of design patterns, look at these frameworks Why use these patterns, than you look at harvest certainly be more.