其他分享
首页 > 其他分享> > 建造者模式

建造者模式

作者:互联网


1. 类图

image.png

2. 示例

将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示

2.1 创建者接口

public abstract class AbstractBuilder {
    Meal meal = new Meal();
    public abstract void buildFood();
    public abstract void buildDrink();
    public Meal getMeal(){return meal;}
}

2.2 接口实现

public class SetMealA extends AbstractBuilder {
    public void buildFood() {meal.setFood("油条");}
    public void buildDrink() {meal.setDrink("豆浆");}
}

public class SetMealB extends AbstractBuilder {
    public void buildFood() {meal.setFood("面包");}
    public void buildDrink() {meal.setDrink("牛奶");}
}

2.3 具体产品

public class Meal {
    private String food;
    private String drink;

    public void setFood(String food) {
        this.food = food;
    }

    public void setDrink(String drink) {
        this.drink = drink;
    }

    @Override
    public String toString() {
        return "Meal{" +
                "food='" + food + '\'' +
                ", drink='" + drink + '\'' +
                '}';
    }
}

2.4 指挥者

public class Director {
    private AbstractBuilder builder;
    public Director(AbstractBuilder builder) {this.builder = builder;}

    public Meal provideMeal() {
        builder.buildFood();
        builder.buildDrink();
        return builder.getMeal();
    }
}

2.4 客户端

public class Client {
    public static void main(String[] args) {
        System.out.println(new Director(new SetMealA()).provideMeal());
    }
}

3. 优点

标签:String,food,builder,建造,模式,public,void,meal
来源: https://blog.csdn.net/danadreamer/article/details/116422068