建造者模式
Posted zhenhong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了建造者模式相关的知识,希望对你有一定的参考价值。
一、大致构造
1、导演者类
2、建造抽象类
3、产品抽象类
4、产品具体类
5、建造具体类
二、代码(建造模式,相当于将一堆零件组装成一个对象)
1、建造抽象类
Builder.java
package com.builderModel; public interface Builder { public void BuildPart1(); public void BuildPart2(); public Product getProduct(); }
2、产品标识类
package com.builderModel; public interface Product { }
3、具体产品类
Article.java
package com.builderModel; public class Article implements Product { private String title; private String content; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "Article [title=" + title + ", content=" + content + "]"; } }
AutoMessage.java
package com.builderModel; public class AutoMessage implements Product { private String from; private String content; public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "Message [from=" + from + ", content=" + content + "]"; } }
4、具体产品构造者
ArticleBuilder.java
package com.builderModel; public class ArticleBuilder implements Builder { Article article = new Article(); @Override public void BuildPart1() { article.setTitle("hello"); } @Override public void BuildPart2() { article.setContent("world"); } @Override public Product getProduct() { return article; } }
AutoMessageBuilder.java
package com.builderModel; public class AutoMessageBuilder implements Builder { private AutoMessage message = new AutoMessage(); @Override public void BuildPart1() { message.setFrom("客户"); } @Override public void BuildPart2() { message.setContent("你的网页出错了"); } @Override public Product getProduct() { return message; } }
5、导演者类
Director.java
package com.builderModel; public class Director { private Builder builder = null; public Director(Builder builder) { this.builder = builder; this.builder.BuildPart1(); this.builder.BuildPart2(); } public Product getProduct() { return this.builder.getProduct(); } }
6、测试类
Test.java
package com.builderModel; public class Test { public static void main(String[] args) { Builder builder = new AutoMessageBuilder(); Director director = new Director(builder); AutoMessage autoMessage = (AutoMessage) director.getProduct(); System.out.println(autoMessage.toString()); } }
以上是关于建造者模式的主要内容,如果未能解决你的问题,请参考以下文章