Simple Factory mode We can also be understood as a class responsible for the production of objects , in our usual programming, when using the "new" keyword to create an object, at this time the class is dependent on the object, that is, the coupling between them is high, when the demand changes, we have to modify this type of source, At this point we can use object-oriented (OO) very important principles to solve this problem, the principle is- package change, since to encapsulate the change, it is natural to find the change of code, and then the change of code in class to encapsulate , One such idea is how our simple factory model is implemented.
namespacesimplefactory{/// <summary> ///the customer acts as a client and is responsible for invoking a simple factory to produce objects///The Chef (equivalent to a simple factory) is responsible for cooking (the object of production)./// </summary> classCustomer {Static voidMain (string[] args) { //customers want to order a tomato scrambled eggFood food1 = Foodsimplefactory.createfood ("scrambled eggs with tomatoes"); Food1. Print (); //customers want to order a potato shredded porkFood FOOD2 = Foodsimplefactory.createfood ("shredded potatoes"); Food2. Print (); Console.read (); } } /// <summary> ///Vegetable Abstract class/// </summary> Public Abstract classFood {//What's the point of the output? Public Abstract voidPrint (); } /// <summary> ///tomato scrambled egg this dish/// </summary> Public classTomatoscrambledeggs:food { Public Override voidPrint () {Console.WriteLine ("a tomato scrambled egg! "); } } /// <summary> ///potato, shredded pork, this dish ./// </summary> Public classShreddedporkwithpotatoes:food { Public Override voidPrint () {Console.WriteLine ("a slice of shredded potatoes"); } } /// <summary> ///Simple Factory class, responsible for cooking/// </summary> Public classFoodsimplefactory { Public StaticFood Createfood (stringtype) { Food and food=NULL; if(Type. Equals ("shredded potatoes") ) { food=Newshreddedporkwithpotatoes (); } Else if(Type. Equals ("scrambled eggs with tomatoes") ) { food=NewTomatoscrambledeggs (); } returnFood ; } }}
Detail: C # design mode (2)--Simple Factory mode
Simple Factory mode of C # design mode