资源来源 菜鸟教程
实现一
创建一个食物条目和食物的包装的接口
Item.java
public interface Item {
public String name();//名称
public Packing packing();//包装
public float price();//价格
}
Packing.java
/**
* 食物包装接口
*/
public interface Packing {
public String pack();
}
实现二
创建实现Packing接口的实现类
Bottle.java
/**
* 瓶子类
*/
public class Bottle implements Packing {
@Override
public String pack() {
return "Bottle";
}
}
Wrapper.java
/**
* 包装纸类
*/
public class Wrapper implements Packing {
@Override
public String pack() {
return "Wrapper";
}
}
实现三
创建Item接口的抽象类,该类提供了默认的功能
Burger.java
public abstract class Burger implements Item {
@Override
public Packing packing() {
return new Wrapper();
}
@Override
public abstract float price();
}
ColdDrink.java
public abstract class ColdDrink implements Item {
@Override
public Packing packing() {
return new Bottle();
}
@Override
public abstract float price() ;
}
实现四
创建扩展了Burger 和ColdDrink的实体类
Coke.java
/**
* 可口可乐 继承 饮料抽象类
*/
public class Coke extends ColdDrink {
@Override
public String name() {
return "Coke{可口可乐}";
}
@Override
public float price() {
return 30.0f;
}
}
Pepsi.java
/**
* 百事可乐 继承饮料抽象类
*/
public class Pepsi extends ColdDrink {
@Override
public String name() {
return "Pepsi{百事可乐}";
}
@Override
public float price() {
return 35.0f;
}
}
ChickenBurger.java
/***
* 鸡肉汉堡
*/
public class ChickenBurger extends Burger {
@Override
public String name() {
return "ChickenBurger {鸡肉汉堡}";
}
@Override
public float price() {
return 50.0f;
}
}
VegBurger.java
/**
* 蔬菜汉堡
*/
public class VegBurger extends Burger {
@Override
public String name() {
return "VegBurger{蔬菜汉堡}";
}
@Override
public float price() {
return 25.0f;
}
}
实现五
创建一个Meal 类,带有上面的item对象
Meal .java
public class Meal {
List<Item> items= new ArrayList<Item>();
public void addItem(Item item){
items.add(item);
}
public float getCost(){
float cost=0.0f;
for (Item item: items) {
cost+=item.price();
}
return cost;
}
public void showItems(){
for (Item item: items ) {
System.err.println("名称"+item.name());
System.err.println(", 包装 :"+item.packing().pack());
System.err.println(", 价格 :"+item.price());
}
}
}
实现六
创建一个MealBuilder类,实际的Builder类负责创建Meal对象
MealBuilder.java
public class MealBuilder {
public Meal preparVegMeal(){
Meal meal = new Meal();
meal.addItem(new VegBurger());
meal.addItem(new Coke());
return meal;
}
public Meal prepareNonVegMeal(){
Meal meal = new Meal();
meal.addItem(new ChickenBurger());
meal.addItem(new Pepsi());
return meal;
}
}
实现七
使用MealBuilder演示建造者模式
public static void main (String[] ages){ //建造者模式
MealBuilder mealBuilder = new MealBuilder();
System.out.println("Non -Veg Meal");
Meal meal = mealBuilder.prepareNonVegMeal();
meal.showItems();
System.err.println("总共消费"+meal.getCost());
System.out.println("Veg Meal");
Meal meal1 = mealBuilder.preparVegMeal();
meal1.showItems();
System.err.println("总共消费"+meal1.getCost());
}
测试结果