OOP: Builder Design pattern
BlitzMax Forums/BlitzMax Tutorials/OOP: Builder Design pattern
| ||
Basic BlitzmaxPort of http://en.wikipedia.org/wiki/Builder_pattern The Builder Pattern is a software design pattern. The intention is to separate the construction of a complex object from its representation so that the same construction process can create different representations. Builder Abstract interface for creating objects(product). Concrete Builder Provide implementation for Builder. Construct and assemble parts to build the objects. Director The Director class is responsible for managing the correct sequence of object creation. It receives a Concrete Builder as a parameter and executes the necessary operations on it. Product The complex object under construction. SuperStrict ' Declare Product Type Pizza ' Type Data Fields Field _dough:String = "" Field _sauce:String = "" Field _topping:String = "" ' Implementation of setter and getter Methods Method setDough(dough:String) Self._dough = dough EndMethod Method getDough:String() Return _dough EndMethod Method setSauce(sauce:String) Self._sauce = sauce EndMethod Method getSauce:String() Return _sauce EndMethod Method setTopping(topping:String) Self._topping = topping EndMethod Method getTopping:String() Return _topping EndMethod EndType ' Abstract Builder Type PizzaBuilder Field _pizza:Pizza Method getPizza:Pizza() Return _pizza EndMethod Method createNewPizzaProduct() _pizza = New Pizza EndMethod Method buildDough() Abstract Method buildSauce() Abstract Method buildTopping() Abstract EndType ' Concrete Builder Type HawaiianPizzaBuilder Extends PizzaBuilder Method buildDough() _pizza.setDough("cross"); EndMethod Method buildSauce() _pizza.setSauce("mild"); EndMethod Method buildTopping() _pizza.setTopping("ham+pineapple") EndMethod EndType ' Concrete Builder Type SpicyPizzaBuilder Extends PizzaBuilder Method buildDough() _pizza.setDough("pan baked"); EndMethod Method buildSauce() _pizza.setSauce("hot"); EndMethod Method buildTopping() _pizza.setTopping("pepperoni+salami") EndMethod EndType ' Director Type Cook Field _builder:PizzaBuilder Method setPizzaBuilder(pb:PizzaBuilder ) _builder = pb EndMethod Method getPizza:Pizza() Return _builder.getPizza() EndMethod Method constructPizza() _builder.createNewPizzaProduct() _builder.buildDough() _builder.buildSauce() _builder.buildTopping() EndMethod EndType 'TestCase Local chief:Cook = New Cook Local hawaiianBuilder:PizzaBuilder = New HawaiianPizzaBuilder Local spicyBuilder:PizzaBuilder = New SpicyPizzaBuilder chief.setPizzaBuilder(hawaiianBuilder) chief.constructPizza() Local mypizza:Pizza = chief.getPizza() Print "Pizza 1" Print mypizza.getDough() Print mypizza.getSauce() Print mypizza.getTopping() chief.setPizzaBuilder(spicyBuilder) chief.constructPizza() Local myotherpizza:Pizza = chief.getPizza() Print "Pizza 2" Print myotherpizza.getDough() Print myotherpizza.getSauce() Print myotherpizza.getTopping() |