码迷,mamicode.com
首页 > 编程语言 > 详细

Java建造者模式

时间:2018-03-25 23:06:16      阅读:348      评论:0      收藏:0      [点我收藏+]

标签:ddr   rri   public   int   分享   get   system   stat   image   

技术分享图片

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建造者模式

标签:ddr   rri   public   int   分享   get   system   stat   image   

原文地址:https://www.cnblogs.com/softwarecrash/p/8647360.html

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