構(gòu)造器模式_組裝復(fù)雜實(shí)例(逐步構(gòu)造出一個(gè)復(fù)雜的實(shí)例
/** * 指揮者 * @author maikec * @date 2019/5/11 */ public class Director { private final AbstractBuilder builder; public Director(AbstractBuilder builder){ this.builder = builder; } public void builderMessage(){ builder.createHead(); builder.createBody(); builder.signature(); } } /** * 抽象構(gòu)造器 * @author maikec * @date 2019/5/11 */ public abstract class AbstractBuilder { protected Message message; protected Head head; protected Body body; protected Author author; /** * 創(chuàng)建消息頭部 * @return */ protected abstract Head createHead(); /** * 創(chuàng)建消息體 * @return */ protected abstract Body createBody(); /** * 署名 * @return */ protected abstract Author signature(); public Message getMessage(){ return message; } } /** * @author maikec * @date 2019/5/11 */ public class Message { private Head head; private Body body; private Author author; public Message(){} public Message(Head head,Body body,Author author){ this.head = head; this.body = body; this.author = author; } @Override public String toString() { super.toString(); if (head !=null || body != null || author != null){ StringBuffer sb = new StringBuffer( "[" ); if (head != null){ sb.append( head.toString() ); } if (body != null){ sb.append( body.toString() ); } if (author != null){ sb.append( author.toString() ); } sb.append( "]" ); return sb.toString(); } return null; } } /** * @author maikec * @date 2019/5/11 */ public class Head { private String name; public Head(){} public Head(String name){ this.name = name; } @Override public String toString() { super.toString(); return name == null ? "Head" : name; } } /** * @author maikec * @date 2019/5/11 */ public class Body { private String name; public Body(){} public Body(String name) { this.name = name; } @Override public String toString() { super.toString(); return name == null ? "Body" : name; } } /** * @author maikec * @date 2019/5/11 */ public class Author { private String name; public Author(){} public Author(String name) { this.name = name; } @Override public String toString() { super.toString(); return name == null ? "Author" : name; } } /** * Email構(gòu)造器 * @author maikec * @date 2019/5/11 */ public class EmailBuilder extends AbstractBuilder { @Override protected Head createHead() { head = new Head("Email Head"); return head; } @Override protected Body createBody() { body = new Body("Email Body"); return body; } @Override protected Author signature() { author = new Author("maikec"); return author; } @Override public Message getMessage() { return new Message( head,body,author ); } } 附錄github.com/maikec/patt… 個(gè)人GitHub設(shè)計(jì)模式案例 聲明引用該文檔請(qǐng)注明出處 |
|