A summary of a sentence
Deferring the implementation to subclasses, the factory class is not responsible for the creation of the product, but gives the interface that the specific factory must implement.
Plot
In the previous article, the simple factory approach actually violates the design principles. So we're going to take a look at this factory class abstract and derive a factory that specializes in making some kind of cake.
This way, when you add a new program, you will no longer need to modify the factory class.
Look back at the plot:
Xiao Ming is a high school little cock Silk, she likes the next class goddess of the flower of the king. The result was too late to confess.
Today just in time to catch up with Wang Floret's birthday, Xiao Ming intends to buy a delicious cake for her to eat, please. But this time Xiao Ming know a special to do Black Forest cake taste much beautiful. I'm going to buy it in this delicious way.
Task one: Modify the taste and Beauty factory class
First, any taste and beauty will sell cakes, the difference is not monopoly. So let's take this method of selling cakes for abstract operation.
Public Abstract class Weiduomei { publicabstract Cake Buy (); }
Next, we create two stores. One is the Black Forest monopoly, one is the Angel cake monopoly
public class Blackforestweiduomei:weiduomei { public override Cake Buy () {
return
new Blackforestcake (); }} public class Angleweiduomei:weiduomei { public override Cake Buy () { return< /span> new Anglecake (); } }
This changes the factory class to complete, and then add a new store will not be modified. Then, we revise the method of Xiao Ming's classmates
Public classsomeming {//speech Public voidSpeak (stringStrText) {Console.WriteLine ("Xiao Ming said:"+strText); } //Buy Cakes Public voidBuycake () {Weiduomei WDM=NewBlackforestweiduomei (); Cake Cake=WDM. Buy (); Cake. Eat (); } }
Xiao Ming students start a black Forest cake shop, and then in this store to buy operations. At this point the method implementation has been deferred to the subclass operation.
This is the factory model.
Summarize
The factory model defers the implementation of the product approach to subclasses. Meet the principle of open and closed in design principles.
Common scenario: you want users to specify factories and products. Different factories and products can provide different functions.
Select key: whether the plant and product classes are co-born
by~
Creation mode (ii) Factory mode