Simple Factory mode:
The essence of the simple factory model is that a factory class dynamically determines which product class (these product classes inherit from a parent class or interface) should be created, based on the parameters passed in.
Note: Strictly speaking, the simple Factory mode is not a design mode, but it is often used. It has the advantage of decoupling the product creation from the use of the product and processing it separately.
Part of the pattern:
- One user: (Pizzastore in the case)
- A simple factory class: Responsible for creating products
- A set of product classes: (in the case of the abstract pizza class and its specific implementation subclass)
The UML class diagram is as follows:
The specific implementation of the case code:
1, Product user class:
class Pizzastore { // contains an abstract class for a product and a simple factory var pizza:pizza = = Simplepizzafactory ()
// provide pizza method Func Orderpizza (pizzatype:pizzatype) { // Create products from simple Factory (Pizza) Pizza = Simplepizzafactory.createpizza (Pizzatype) // product behavior Pizza.prepare () Pizza.bake () Pizza.cut () Pizza.box ()}}
2, Simple factory class
class simplepizzafactory { = Pizza () // Create Pizza (create different Pizza with different parameters) func Createpizza (Pizzatype:pizzatype), Pizza { switch pizzatype { case Pizzatype.cheese: = Cheesepizza () case Pizzatype.clam: = Clampizza () } return Pizza }}
3. Product class: (contains abstract classes and their specific implementation classes)
classPizza {var name:string=""var dough:string=""var sauce:string=""var toppings:[string]= [] //preparing the Pizza methodFunc Prepare () {println ("preparing for \ (name) ...") println ("tossing dough ...") println ("Adding sauce ...") forTopping:stringinchToppings {println ("\ (Topping)")}}} Func box () {println ("packing ... \ n")} func Bake () {println ("baking ...")} func cut () {println ("cropping ...") }}classCheesepizza:pizza {Overrideinit () {super.init () Self.name="Cheese Pizza"Self.dough="Thin crust Dough"Self.sauce="Marinara Sauce"Toppings.append ("grated Reggino Cheese") }}classClampizza:pizza {Overrideinit () {super.init () Self.name="Clam Pizza"Self.dough="Low crust Dough"Self.sauce="Cherry Sauce"Toppings.append ("grated Reggino Clam") }}
4. Test code
Let Pizzastore = pizzastore ()// get a Cheese Pizza Pizzastore.orderpizza from Pizzastore( Pizzatype.cheese)// get a Clam PizzaPizzastore.orderpizza (Pizzatype.clam) from Pizzastore
5. Test results
Design pattern Learning-Simple Factory mode