建造者模式:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示
简单描述:1个产品类(可有可无,关键是建造流程),1个抽象建造步骤类,多个具体建造子类(不同的类建造不同的产品),1个指挥者(用于规定建造流程),客户端指定需要建造的具体类型,由指挥者建造好之后,建造者子类返回对应产品给客户
大话设计模式中的截图:
例子代码:
Product类:
1 package com.longsheng.builder;
2
3 public class Product {
4
5 private String name;
6 private String price;
7
8 public String getName() {
9 return name;
10 }
11
12 public void setName(String name) {
13 this.name = name;
14 }
15
16 public String getPrice() {
17 return price;
18 }
19
20 public void setPrice(String price) {
21 this.price = price;
22 }
23
24 public void show() {
25 System.out.println("Product_name:" + getName() + "------Product_price"
26 + getPrice());
27 }
28 }
Builder类:
1 package com.longsheng.builder;
2
3 public abstract class Builder {
4
5 public abstract void buildName();
6
7 public abstract void buildPrice();
8
9 public abstract Product createProduct();
10
11 }
具体建造者ConcreteBuilderA类:
1 package com.longsheng.builder;
2
3 public class ConcreteBuilderA extends Builder {
4
5 private Product mPorduct;
6
7 public ConcreteBuilderA() {
8 mPorduct = new Product();
9 }
10
11 @Override
12 public void buildName() {
13 mPorduct.setName("产品1");
14 }
15
16 @Override
17 public void buildPrice() {
18 mPorduct.setPrice("10元");
19 }
20
21 @Override
22 public Product createProduct() {
23 return mPorduct;
24 }
25
26 }
具体建造者ConcreteBuilderB类:
1 package com.longsheng.builder;
2
3 public class ConcreteBuilderB extends Builder {
4
5 private Product mPorduct;
6
7 public ConcreteBuilderB() {
8 mPorduct = new Product();
9 }
10
11 @Override
12 public void buildName() {
13 mPorduct.setName("产品2");
14 }
15
16 @Override
17 public void buildPrice() {
18 mPorduct.setPrice("20元");
19 }
20
21 @Override
22 public Product createProduct() {
23 return mPorduct;
24 }
25
26 }
指挥者Director类:
1 package com.longsheng.builder;
2
3 public class Director {
4
5 public void construct( Builder mBuilder ) {
6 mBuilder.buildName();
7 mBuilder.buildPrice();
8 }
9
10 }
客户端:
1 package com.longsheng.builder;
2
3 public class Cilent {
4
5 public static void main(String[] args) {
6 Director mDirector = new Director();
7 Builder mBuilder1 = new ConcreteBuilderA();
8 Builder mBuilder2 = new ConcreteBuilderB();
9
10 mDirector.construct(mBuilder1);
11 Product mProduct1 = mBuilder1.createProduct();
12 mProduct1.show();
13
14 mDirector.construct(mBuilder2);
15 Product mProduct2 = mBuilder2.createProduct();
16 mProduct2.show();
17 }
18
19 }
建造者的Builder类里的那些构建方法必须足够普遍,以便为各种类型的具体建造者构造
建造者模式实在当创建复杂对象的算法应该独立于该对象的组成部分以及他们的装配方法时使用的模式
建造者模式用于创建一些复杂的对象,这些对象内部构建间的构造顺序通常是稳定的,但对象内部的构建通常面临着复杂的变化
大话设计模式_建造者模式(Java代码),布布扣,bubuko.com
时间: 2024-12-26 07:37:12