java实现建造者设计模式

java实现建造者设计模式

以下是一个使用 Java 语言实现的建造者模式的示例

①定义Pizza对象
class Pizza {

    private String dough;
    private String sauce;
    private List<String> toppings;

    public Pizza(String dough, String sauce, List<String> toppings) {
        this.dough = dough;
        this.sauce = sauce;
        this.toppings = toppings;
    }

    public String getDough() {
        return dough;
    }

    public void setDough(String dough) {
        this.dough = dough;
    }

    public String getSauce() {
        return sauce;
    }

    public void setSauce(String sauce) {
        this.sauce = sauce;
    }

    public List<String> getToppings() {
        return toppings;
    }

    public void setToppings(List<String> toppings) {
        this.toppings = toppings;
    }

    @Override
    public String toString() {
        return "Pizza{" +
                "dough='" + dough + '\'' +
                ", sauce='" + sauce + '\'' +
                ", toppings=" + toppings +
                '}';
    }
}    

Pizza 类是建造者模式的核心类。它定义了 Pizza 对象的属性,并提供了一个构造函数来创建 Pizza 对象。


②定义Pizza对象建造者
class PizzaBuilder {

    private String dough;
    private String sauce;
    private List<String> toppings = new ArrayList<>();

    public PizzaBuilder withDough(String dough) {
        this.dough = dough;
        return this;
    }

    public PizzaBuilder withSauce(String sauce) {
        this.sauce = sauce;
        return this;
    }

    public PizzaBuilder withTopping(String topping) {
        this.toppings.add(topping);
        return this;
    }

    public Pizza build() {
        return new Pizza(dough, sauce, toppings);
    }
}

PizzaBuilder 类是 Pizza 类的建造者类。它提供了一系列方法来设置 Pizza 对象的属性,并提供了一个 build() 方法来创建 Pizza 对象。


③使用建造者构建Pizza对象
public class Main {
    public static void main(String[] args) throws Exception {
        PizzaBuilder pizzaBuilder = new PizzaBuilder();
        pizzaBuilder.withDough("Thin crust");
        pizzaBuilder.withSauce("Tomato");
        pizzaBuilder.withTopping("Pepperoni");
        pizzaBuilder.withTopping("Mushrooms");
        pizzaBuilder.withTopping("Olives");

        Pizza pizza = pizzaBuilder.build();
        System.out.println(pizza);
    }
}

在 main() 方法中,我们创建了一个 PizzaBuilder 对象,并使用它的方法来设置 Pizza 对象的属性。然后,我们调用 build() 方法来创建 Pizza 对象。最后,我们使用 System.out.println() 方法来打印 Pizza 对象的信息。


你可能感兴趣的:(java,设计模式,开发语言,建造者模式)