码迷,mamicode.com
首页 > 其他好文 > 详细

23种设计模式之建造者模式

时间:2017-08-21 15:50:32      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:rtb   bsp   design   div   src   builder   img   port   设计   

建造者模式(Builder):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

技术分享

 技术分享

package designMode.builder;

import java.util.LinkedList;
import java.util.List;

class Product {
    
    List<String> parts = new LinkedList<String>();
    
    public void add(String part){
        parts.add(part);
    }
    
    public void show(){
        System.out.println("产品创建...");
        for (String str : parts) {
            System.out.println(str);
        }
    }
}
package designMode.builder;

interface Builder {
    
    void buildPartA();
    
    void buildPartB();
    
    Product getResult();
}
package designMode.builder;

class ConcreteBuilder1 implements Builder{
    
    private Product product = new Product();

    @Override
    public void buildPartA() {
        product.add("部件A");
    }

    @Override
    public void buildPartB() {
        product.add("部件B");
    }

    @Override
    public Product getResult() {
        return product;
    }

}
class ConcreteBuilder2 implements Builder{
    
    private Product product = new Product();
    
    @Override
    public void buildPartA() {
        product.add("部件X");
    }
    
    @Override
    public void buildPartB() {
        product.add("部件Y");
    }
    
    @Override
    public Product getResult() {
        return product;
    }
}
package designMode.builder;

class Director {
    
    public void construct(Builder builder){
        builder.buildPartA();
        builder.buildPartB();
    }
}
package designMode.builder;

class Test {
    
    public static void main(String[] args) {
        Director director = new Director();
        Builder b1 = new ConcreteBuilder1();
        Builder b2 = new ConcreteBuilder2();
        
        director.construct(b1);
        Product p1 = b1.getResult();
        p1.show();
        
        director.construct(b2);
        Product p2 = b2.getResult();
        p2.show();
    }
}

 

23种设计模式之建造者模式

标签:rtb   bsp   design   div   src   builder   img   port   设计   

原文地址:http://www.cnblogs.com/lxcmyf/p/7404414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!