首页 > 其他 > 详细

建造者模式

时间:2019-12-12 09:23:35      阅读:73      评论:0      收藏:0      [点我收藏+]

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

二、示例代码:

/*产品类*/
public class Product {
    private List<String> parts = new ArrayList<String>();

    public void addPart(String part) {
        parts.add(part);
    }

    public void show() {
        for (String part : parts
        ) {
            System.out.println("产品建造过程");
            System.out.println("装配:" + part);
        }
    }
}
/*抽象建造者类*/
public abstract class Builder {
    public abstract void builderA();

    public abstract void builderB();

    public abstract Product getResult();
}
/*具体建造类*/
public class ConcreteBuilderA extends Builder {
    private Product product = new Product();

    @Override
    public void builderA() {
        product.addPart("part a");
    }

    @Override
    public void builderB() {
        product.addPart("part b");
    }

    @Override
    public Product getResult() {
        return product;
    }
}
/*具体建造类*/
public class ConcreteBuilderB extends Builder {
    private Product product = new Product();

    @Override
    public void builderA() {
        product.addPart("part w");
    }

    @Override
    public void builderB() {
        product.addPart("part q");
    }

    @Override
    public Product getResult() {
        return product;
    }
}
/*指挥者类*/
public class Director {
    public void Constructor(Builder builder) {
        builder.builderA();
        builder.builderB();
    }
}
/*客户端类*/
public class Client {
    public static void main(String[] args) {
        Director director = new Director();
        Builder builder = new ConcreteBuilderA();
        director.Constructor(builder);
        Product product = builder.getResult();
        product.show();
    }
}

建造者模式

原文:https://www.cnblogs.com/yfy-/p/12026766.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!