设计模式(四) Builder

生成器模式:

将一个复杂对象的构建与它的表现分离,使得同样的构建过程可以创建不同的表现。

  • 创建型的模式
  • 构建复杂的对象
  • 分离

案例

class Burger {
    let customerName: String;
    let veggieProduct: Bool;
    let patties: Int;
    let pickles: Bool;
    let mayo: Bool;
    let ketchup: Bool;
    let lettuce: Bool;
    let cook: Cooked;
    
    enum Cooked: String {
        case RARE = "Rare";
        case NORMAL = "Normal";
        case WELLDONE = "Well Done";
    }
    
    init(name: String, veggie: Bool, patties: Int, pickles: Bool,
         mayo: Bool, ketchup: Bool, lettuce: Bool, cook: Cooked) {
        self.customerName = name;
        self.veggieProduct = veggie;
        self.patties = patties;
        self.pickles = pickles;
        self.mayo = mayo;
        self.ketchup = ketchup;
        self.lettuce = lettuce;
        self.cook = cook;
    }
    
    func printDescription() {
        print("Name \(self.customerName)");
        print("Veggie: \(self.veggieProduct)");
        print("patties: \(self.patties)");
        print("pickes: \(self.pickles)");
        print("Mayo: \(self.mayo)");
        print("ketchup: \(self.ketchup)");
        print("lettuce: \(self.lettuce)");
        print("cook: \(self.cook.rawValue)");
    }
}

let order = Burger(name: "Joe", veggie: false, patties: 2, pickles: true, mayo: true, ketchup: true, lettuce: true, cook: Burger.Cooked.NORMAL);
order.printDescription();

builder 重构

  • 增加一个 builder 类
class BurgerBuilder {
    private var veggie      = false;
    private var pickles     = true;
    private var mayo        = true;
    private var ketchup     = true;
    private var lettuce     = true;
    private var cooked      = Burger.Cooked.NORMAL;
    private var patties     = 2;
    
    func setVeggie(choice: Bool) { self.veggie = choice };
    func setPickles(choice: Bool) { self.pickles = choice };
    func setMayo(choice: Bool) { self.mayo = choice };
    func setKetchup(choice: Bool) { self.ketchup = choice };
    func setLettuce(choice: Bool) { self.lettuce = choice };
    func setCooked(choice: Burger.Cooked) { self.cooked = choice };
    func addPatty(choice: Bool) { self.patties = choice ? 3 : 2 };
    
    func buildObject(name: String) -> Burger {
        return Burger(name: name, veggie: veggie, patties: patties, pickles: pickles, mayo: mayo, ketchup: ketchup, lettuce: lettuce, cook: cooked);
    }
}


let builder = BurgerBuilder();
builder.setVeggie(choice: false);
builder.addPatty(choice: false);
let order = builder.buildObject(name: "Joe");
order.printDescription();

优点

  • 修改默认值,不需要修改 Burger
  • 可以在 Builder 内部,做逻辑处理

你可能感兴趣的:(设计模式(四) Builder)