以上实现了用户与产品生产过程的解耦,用户只需要指定想要的产品交给Direct,由他来执行所有的操作
? 创建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