*********************************
简单工厂模式的引入
为什么要引入
*********************************
披萨店 成长的烦恼
程序编得好,要饭要到老。
小明不信邪,决定开一家 披萨店。
then you’d add some code that determines the appropriate type of pizza and then goes about making the pizza:
We’re now passing in the type of pizza to orderPizza.
Based on the type of pizza, we instantiate the correct concrete class and assign it to the pizza instance variable.
Note that each pizza here has to implement the Pizza interface.
Once we have a Pizza, we prepare it (you know, roll the dough, put on the sauce and add the toppings & cheese),then we bake it, cut it and box it!
Each Pizza subtype (CheesePizza, VeggiePizza, etc.) knows how to prepare itself.
But the pressure is on to add more pizza t ypes
You realize that all of your competitors have added a couple of trendy pizzas to their menus: the Clam Pizza and the Veggie Pizza.
This code is NOT closed for modification.
If the Pizza Shop changes its pizza offerings, we have to get into this code and modify it.
Clearly, dealing with which concrete class is instantiated is really messing up our orderPizza() method and preventing it from being closed for modification.
But now that we know what is varying and what isn’t, it’s probably time to encapsulate it.
Encapsulating object creation
So now we know we’d be better off moving the object creation out of the orderPizza() method.
But how? Well, what we’re going to do is take the creation code and move it out into another object that is only going to be concerned with
creating pizzas.
Factories handle the details of object creation.
Once we have a SimplePizzaFactory, our orderPizza() method just becomes a client of that object.
Any time it needs a pizza it asks the pizza factory to make one.
We’ve still got a few details to fill in here; for instance, what does the orderPizza() method replace its creation code with?
Let’s implement a simple factory for the pizza store and find out
Building a simple pizza factory
What we’re going to do is define a class that encapsulates the object creation for all pizzas. Here it is...
Here’s our new class, the SimplePizzaFactory. It has one job in life: creating pizzas for its clients.
First we define a createPizza() method in the factory. This is the method all clients will use to instantiate new objects
Reworking the PizzaStore class
Now it’s time to fix up our client code. What we want to do is rely on the factory to create the pizzas for us. Here are the changes:
Now we give PizzaStore a reference to a SimplePizzaFactory.
PizzaStore gets the factory passed to it in the constructor.
And the orderPizza() method uses thefactory to create its pizzas by simply passing on the type of the order.