構造器模式_組裝複雜實例(逐步構造出一個複雜的實例 附錄 github.com/maikec/patt… 個人GitHub設計模式案例 聲明 引用該文檔請註明出處 ...
構造器模式_組裝複雜實例(逐步構造出一個複雜的實例
/** * 指揮者 * @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(); } } /** * 抽象構造器 * @author maikec * @date 2019/5/11 */ public abstract class AbstractBuilder { protected Message message; protected Head head; protected Body body; protected Author author; /** * 創建消息頭部 * @return */ protected abstract Head createHead(); /** * 創建消息體 * @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構造器 * @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… 個人GitHub設計模式案例
聲明
引用該文檔請註明出處