建造者模式(Builder Pattern)
将一个复杂对象的创建与它的表示分离,使得同样的创建过程有不同的表示,用户只用知道创建类型,无需知道创建的过程。简而言之,用户只用知道对象名称,和他/她有的参数,然后传递,其余的事情我们在创建类内部进行操作。例如,用过jpa的都知道,我们只用传递我们的查询条件,然后赋值给类,然后把类传入方法,他的底层就会生成sql并且执行。这就是建造者模式的一个例子。
@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