一、前言:
二、代码实现:
1、客户端调用:
//收银台
Builder builder = new HolidayBuilder();
//以下是模板代码,不轻易更改
builder.buildApple(120);
builder.buildBanana(80);
builder.buildOrange(50);
FruitMeal fruitMeal = builder.getFruitMeal();
int cost = fruitMeal.cost();
Log.d("LUO", "本次共花费:" + cost);
2、创建Builder :
//创建一个MealBuilder类,实际的builder类负责创建套餐Meal对象。
//也是工厂
public interface Builder {
void buildApple(int price);//设置苹果
void buildBanana(int price);//设置香蕉
void buildOrange(int price);//设置橘子
FruitMeal getFruitMeal();//返回创建的套餐
}
3、创建一个水果套餐Meal类
//创建一个水果套餐Meal类
public class FruitMeal {
private Apple apple;//苹果--价格
private Banana banana;//香蕉价格
private Orange orange; //桔子价格
private int discount;//折扣价
private int totalPrice;//套餐总价
public Apple getApple() {
return apple;
}
public void setApple(Apple apple) {
this.apple = apple;
}
public Banana getBanana() {
return banana;
}
public void setBanana(Banana banana) {
this.banana = banana;
}
public Orange getOrange() {
return orange;
}
public void setOrange(Orange orange) {
this.orange = orange;
}
public int getDiscount() {
return discount;
}
public void setDiscount(int discount) {
this.discount = discount;
}
public int getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(int totalPrice) {
this.totalPrice = totalPrice;
}
public int cost(){
return this.totalPrice;
}
public void init() {
if (null != apple){
totalPrice += apple.price();
}
if (null != orange){
totalPrice += orange.price();
}
if (null != banana){
totalPrice += banana.price();
}
if (totalPrice > 0){
totalPrice -= discount;
}
}
public void showItems() {
Log.d("LUO","totalPrice:" + totalPrice);
}
}
4、创建HolidayBuilder
public class HolidayBuilder implements Builder{
private FruitMeal fruitMeal = new FruitMeal();
@Override
public void buildApple(int price) {
Apple apple = new Apple();
apple.setPrice(price);
fruitMeal.setApple(apple);
}
@Override
public void buildBanana(int price) {
Banana banana = new Banana();
banana.setPrice(price);
fruitMeal.setBanana(banana);
}
@Override
public void buildOrange(int price) {
Orange fruit = new Orange("Peter",80);
fruit.setPrice(price);
fruitMeal.setOrange(fruit);
}
@Override
public FruitMeal getFruitMeal() {
fruitMeal.setDiscount(15);//折扣价格对一个套餐来,是固定的
fruitMeal.init();
return fruitMeal;
}
}