纯粹学习笔记。
使用多个简单的对象构造成复杂对象。
一个builder会一步一步的构造成最终的对象。该builder类是独立于其他对象的。
主要用在一个复杂对象的创建。每个子对象实现逻辑可以改变,但是组合在一起之后的逻辑不变。
适用场景:生成的对象具有复杂的内部结构。生成的对象内部本身相互依赖。
案例
一个套餐: 汉堡(Burger)和冷饮(Colddrink),汉堡可以是素食汉堡和鸡肉汉堡,包装是纸质的。冷饮可以是可乐(coke)和百事(pepsi),包装是瓶子。
Item.java
public interface Item {
public String name();
public Packing packing();
public float price();
}
Packing.java
public interface Packing {
public String pack();
}
创建Packing接口的实体类。
Wrapper.java
public class Wrapper implements Packing {
@Override
public String pack() {
return "Wrapper";
}
}
Bottle.java
public class Bottle implements Packing {
@Override
public String pack() {
return "Bottle";
}
}
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();
}
VegBurger.java
public class VegBurger extends Burger {
@Override
public String name() {
return "VegBurger";
}
@Override
public float price() {
return 25.0f;
}
}
ChickenBurger.java
public class ChickenBurger extends Burger {
@Override
public String name() {
return "ChickenBurger";
}
@Override
public float price() {
return 50.5f;
}
}
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;
}
}
Meal.java
import java.util.ArrayList;
import java.util.List;
public class Meal {
private List<Item> items = new ArrayList<Item>();
public void addItem(Item item) {
Items.add(item);
}
public float getCoat() {
float coats = 0.0f;
for (Item item : items) {
coat += item.price();
}
return coats;
}
}
MealBuilder.java
public class MealBuilder {
public Meal prepareVegMeal (){
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;
}
}
网友评论