创建型模式之建造者模式

时间:2020-06-07 18:45:26   收藏:0   阅读:35

建造者模式

1.基本介绍:

2.建造者模式的四个角色:

3.角色关系如下(建造者模式原理图):

技术分享图片

以上实现了用户与产品生产过程的解耦,用户只需要指定想要的产品交给Direct,由他来执行所有的操作

4.JDK的StringBuilder分析

1.角色分析

2.源码分析

? 创建StringBuilder对象时传入字符串,传入的字符串就相当于指定产品类型

//构造方法中调用了append()方法,该方法是属于上述模式中的生产方法,所以这里的StringBuilder即是指挥者也是具体建造者
public StringBuilder(String str) {
    super(str.length() + 16);
    append(str);
}
//append方法中它调用了父类的append()
@Override
public StringBuilder append(String str) {
    super.append(str);
    return this;
}

进入到super.append()中

//AbstractStringBuilder实现了Appendable,他是具体的建造者,在这里完成了一个具体的操作
abstract class AbstractStringBuilder implements Appendable, CharSequence {    
	public AbstractStringBuilder append(String str) {
        if (str == null)
            return appendNull();
        int len = str.length();
        ensureCapacityInternal(count + len);
        str.getChars(0, len, value, count);
        count += len;
        return this;
    }

Appendable定义了多个append接口,由他的实现类去实现

 public interface Appendable {
    Appendable append(CharSequence csq) throws IOException;
    Appendable append(CharSequence csq, int start, int end) throws IOException;
    Appendable append(char c) throws IOException;
}

可以发现,设计模式不一定要按照我们的原理图来设定,应该使用的是设计模式的思想

抽象工厂与建造者模式的区别

小结

原文:https://www.cnblogs.com/JIATCODE/p/13061450.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!