Java建造者模式

Posted softwarecrash

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java建造者模式相关的知识,希望对你有一定的参考价值。

技术分享图片

Meal:

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

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

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

MealBuilder:

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

SubMealBuilderA:

public class SubMealBuilderA extends MealBuilder {
    @Override
    public void buildFood() {
        System.out.println("This is SubMealBuilderA food!");
    }

    @Override
    public void buildDrink() {
        System.out.println("This is SubMealBuilderA Drink!");
    }
}

SubMealBuilderB:

public class SubMealBuilderB extends MealBuilder{
    @Override
    public void buildFood() {
        System.out.println("This is SubMealBuilderB food!");
    }

    @Override
    public void buildDrink() {
        System.out.println("This is SubMealBuilderB drink!");
    }
}

KFCWaiter:

public class KFCWaiter {
    private MealBuilder mb = null;

    public KFCWaiter(){

    }

    public KFCWaiter(MealBuilder mb){
        this.mb = mb;
    }

    public void setMealBuilder(MealBuilder mb){
        this.mb = mb;
    }

    public Meal construct(){
        mb.buildDrink();
        mb.buildFood();
        return mb.getMeal();
    }
}

BuilderMethod(调用):

public class BuilderMethod{
    public static void main(String[] args){
        MealBuilder mb_1 = new SubMealBuilderA();
        MealBuilder mb_2 = new SubMealBuilderB();

        KFCWaiter kfc = null;

        kfc = new KFCWaiter(mb_1);
        kfc.construct();

        kfc = new KFCWaiter(mb_2);
        kfc.construct();
    }
}

Result:

This is SubMealBuilderA Drink!
This is SubMealBuilderA food!
This is SubMealBuilderB drink!
This is SubMealBuilderB food!




以上是关于Java建造者模式的主要内容,如果未能解决你的问题,请参考以下文章

java设计模式--建造者模式(Builder)

Java设计模式菜鸟系列(十五)建造者模式建模与实现

JAVA设计模式:建造者模式原理与代码理解

java常用设计模式四:建造者模式

Java设计模式之建造者模式

Java设计模式图文代码案例详解Java五大创建者模式 建造者原型(抽象)工厂单例模式