(Builder Pattern)
(Builder Pattern)
Separating the creation of a complex object from its representation makes the same creation process have different representations, and the user only needs to know the creation type, but not the creation process。In short, the user just needs to know the object name, and the parameters he/she has, and then pass it on, and we do the rest inside the creation class。For example, anyone who has ever used JPA knows that we just pass our query criteria, assign a value to the class, pass the class into the method, and the underlying SQL will be generated and executed. This is an example of Builder Mode.
@Data @ToString public class Course { String name; String blog; String video; String note; } public class CourseBuilder { Course course = new Course(); CourseBuilder addName(String name) { course.setName(name); return this; } CourseBuilder addBlog(String blog) { course.setBlog(blog); return this; } CourseBuilder addVideo(String video) { course.setVideo(video); return this; } CourseBuilder addNote(String note) { course.setNote(note); return this; } Course builder() { return course; } }
To test
public class Test { public static void main(String[] args) { CourseBuilder builder=new CourseBuilder(); System.out.println(builder.addBlog("Builder").addName("Java").addNote("Node").addVideo("Video").builder().toString()); } }
To explain
The code above are a simple example for Builder Pattern, it is easy to understand, isn't it ? The main difficulty is that we shoud do many things in classess of Builder, you can imagine, client pass on irregular params into you classes of bulider,but we know some params shoud be arrange,such as 'order by' of sql it shoud be arrange into the end.so we have to make many logic in classes of builder
Apply into souce of code
java.lang.StringBuilder#append(java.lang.String)
org.apache.ibatis.mapping.CacheBuilder#properties
org.apache.ibatis.session.SqlSessionFactoryBuilder#build(java.io.Reader)
org.springframework.beans.factory.support.BeanDefinitionBuilder#getBeanDefinition
Sum up
advantages:
- Encapsulation:client just should know what params they shoud pass on
disadvantages:
- if demands are changed,we have to change logic in classess of builder,if fields are change we must change classess of builder as well
- you have to make monstrous logical code in your classes of bulider
compare with factory pattern
- differnet in ways:classes created by Builder pattern are different, but the classess created by Factory pattern are same
- different in focus:Factory pattern just need create classes ,but Builder pattern need to assemble
tips:
we can assign default value, if client can not pass on params,we also can personalize arithmetic in classes of bulider which make code perform batter. in short,more individual and convenient than Factory pattern






浙公网安备 33010602011771号