Introduction to simple factory Mode
Simple factory mode: Return instances of one of several possible classes based on the data provided to it. Generally, the classes returned by this method have a common parent class and a common method, but each method executes different tasks and is optimized based on different data.
Instance
Example: A name consists of a surname and a name. Assume that there are two input formats: "horse, Cloud" and "horse cloud". One is "," and the other is space. The first and last names must be retrieved.
Code implementation to create a parent class
class SplitName { private string frName, lName; public string LName { get { return lName; } set { lName = value; } } public string FrName { get { return frName; } set { frName = value; } } }
Create a comma-separated name class
class CommaSplit:SplitName { public CommaSplit(string name) { int i = name.IndexOf(","); if (i > 0) { FrName = name.Substring(0, i); LName = name.Substring(i + 1); } else { FrName = name; LName = ""; } } }
Create a space-separated name class
class BlankSplit:SplitName { public BlankSplit(string name) { int i = name.IndexOf(" "); if (i > 0) { FrName = name.Substring(0, i); LName = name.Substring(i + 1); } else { FrName = name; LName = ""; } } }
Create a factory
class NameFactory { public NameFactory() { } public SplitName getName(string name) { if (name.IndexOf(",") > 0) { return new CommaSplit(name); } else { return new BlankSplit(name); } } }
Application factory Model
Class program {static void main (string [] ARGs) {console. writeline ("enter your name:"); string name = console. readline (); namefactory = new namefactory (); splitname spname = namefactory. getname (name); console. writeline ("Your surname is {0}", spname. frname); console. writeline ("Your name {0}", spname. lname); console. readkey (true );}}
Summary:
A good programming mode makes the program highly available and easy to maintain in the future, learning programming at 1.1 points. Note: The comma in the program is a comma in Chinese.
Simple factory Mode