Design Mode-factory mode, design mode factory Mode

Source: Internet
Author: User

Design Mode-factory mode, design mode factory Mode

1: simple factory Model

In simple factory mode, I personally think it is to separate the client program from the class object. The user does not consider which method to call, I only need to tell you some of my features to call the corresponding objects. The following uses people from different nationalities to describe them.

A: If we want to develop a function to count Chinese, American, and Japanese people, we will first consider creating an interface for basic operations on people.

1 public interface IPerson 2 {3 /// <summary> 4 /// add 5 /// </summary> 6 /// <param name = "person"> </ param> 7 // <returns> </returns> 8 bool Add (Person person ); 9 10 /// <summary> 11 /// delete 12 /// </summary> 13 /// <param name = "id"> </param> 14 // /<returns> </returns> 15 bool Delete (string id ); 16 17 /// <summary> 18 /// modify 19 /// </summary> 20 /// <param name = "person"> </param> 21 // /<returns> </returns> 22 bool Update (Person person ); 23 24 /// <summary> 25 /// obtain 26 /// </summary> 27 /// <param name = "id"> </param> 28 // /<returns> </returns> 29 bool Get (string id ); 30}Human behavior Interface

B: Define an enumeration from different nationalities

1 /// <summary> 2 // enumeration indicating Nationality 3 /// </summary> 4 public enum Nationality {5 [Description ("Chinese Nationality")] 6 China = 0, 7 [Description ("American nationality")] 8 America = 1, 9 [Description ("Japanese nationality")] 10 Japan = 211}Define Enumeration

C: Implementation Interface Class

1 public class ChinaPerson: IPerson {2 private readonly string _ conn; 3 4 public ChinaPerson () 5 {6 _ conn = ConfigurationManager. connectionStrings ["dblink"]. connectionString; 7} 8 9 public bool Add (Person person) 10 {11 const string SQL = "insert into china (Id, UserName, RealName, Nationality, AddDate) values (@ Id, @ UserName, @ RealName, @ Nationality, @ AddDate) "; 12 var parameters = new [] 13 {14 new MySqlParameter (" @ Id ", person. id), 15 new MySqlParameter ("@ UserName", person. userName), 16 new MySqlParameter ("@ RealName", person. realName), 17 new MySqlParameter ("@ Nationality", person. nationality), 18 new MySqlParameter ("@ AddDate", person. addDate) 19}; 20 return MySqlHelper. executeNonQuery (_ conn, CommandType. text, SQL, parameters)> 0; 21} 22 23 public bool Delete (string id) 24 {25 const string SQL = "delete from china where Id = @ id "; 26 var parameters = new [] 27 {28 new MySqlParameter ("@ Id", id) 29}; 30 return MySqlHelper. executeNonQuery (_ conn, CommandType. text, SQL, parameters)> 0; 31} 32 33 public bool Update (Person person) 34 {35 throw new NotImplementedException (); 36} 37 38 public Person Get (string id) 39 {40 const string SQL = "select * from china where Id = @ Id"; 41 var parameters = new [] 42 {43 new MySqlParameter ("@ Id", id) 44}; 45 var mySqlHelper = new MySqlHelper (_ conn); 46 var dateReader = mySqlHelper. executeDataReader (CommandType. text, SQL, parameters); 47 var p = new Person (); 48 while (dateReader. read () 49 {50 p. id = dateReader ["Id"]. toString (); 51 p. userName = dateReader ["UserName"]. toString (); 52 p. nationality = (Nationality) dateReader ["Nationality"]; 53 p. realName = dateReader ["RealName"]. toString (); 54} 55 return p; 56} 57}Implementation Interface Class

D: The factory returns different implementation Objects Based on the client type.

1 public class SimpleFactory 2 {3 public static IPerson Create (Nationality nationality) 4 {5 switch (nationality) 6 {7 case Nationality. china: 8 return new ChinaPerson (); 9 break; 10 case Nationality. america: 11 return new AmericaPerson (); 12 break; 13 case Nationality. japan: 14 return new Japan person (); 15 break; 16 default: 17 throw new Exception ("parameter mismatch, please verify"); 18 break; 19} 20}Factory

E: client call

1 // China 2 IPerson chinaPerson = SimpleFactory. create (Nationality. china); 3 bool result = chinaPerson. add (new Person 4 {5 Id = Guid. newGuid (). toString (), 6 UserName = "zs", 7 RealName = "zhangsan", 8 Nationality = Nationality. china, 9 AddDate = DateTime. now10}); 11 if (result) 12 {13 Console. writeLine ("successfully added"); 14} 15 var p = chinaPerson. get ("6a41924f-804b-4425-b5ab-19ab1_11511"); 16 Console. writeLine (string. format ("I am {0}, from China", p. realName); 17 18 // US 19 IPerson americaPerson = SimpleFactory. create (Nationality. america); 20 bool result1 = americaPerson. add (new Person21 {22 Id = Guid. newGuid (). toString (), 23 UserName = "ls", 24 RealName = "", 25 Nationality = Nationality. america, 26 AddDate = DateTime. now27}); 28 if (result1) {29 Console. writeLine ("successfully added"); 30} 31 var person = americaPerson. get ("91955e6d-c6cc-4a25-933f-243753d12b9a"); 32 Console. writeLine (string. format ("I am {0}, from the United States", person. realName ));Client call

F: view results

OK. The whole process is a simple factory.

Note:

1: when setting up a simple factory, I personally think that it is best to enumerate the parameters or write them in the configuration file. The advantage is that you can modify the enumeration or configuration file later. The error probability will be much reduced.

Advantage: the use of simple factory in line with the low coupling idea, let the customer program and specific implementation object separation, when modifying a specific implementation object, you only need to modify the logic in the factory and do not need to modify the client.

Disadvantage: it does not comply with the open and closed principle, because when an object is added, the factory needs to be modified. Any modification may affect the stability of the existing project, at the same time, if there are 50 objects, you can switch 50 times. This is too much.

2: factory Model

The factory mode is an extension of the simple factory mode with high flexibility. When you need to create a person of a new nationality, you only need to add and not modify the existing code, this ensures the stability of the original project.

First look at a simple figure

A: First, create an abstract interface.

1 public interface IPerson 2 {3 /// <summary> 4 /// add 5 /// </summary> 6 /// <param name = "person"> </ param> 7 // <returns> </returns> 8 bool Add (Person person ); 9 10 /// <summary> 11 /// delete 12 /// </summary> 13 /// <param name = "id"> </param> 14 // /<returns> </returns> 15 bool Delete (string id ); 16 17 /// <summary> 18 /// modify 19 /// </summary> 20 /// <param name = "person"> </param> 21 // /<returns> </returns> 22 bool Update (Person person ); 23 24 /// <summary> 25 /// obtain 26 /// </summary> 27 /// <param name = "id"> </param> 28 // /<returns> </returns> 29 Person Get (string id ); 30}Interface

B: Create an object class that inherits this abstract interface.

1 /// <summary> 2 // japanese factory class 3 /// </summary> 4 public class JapanFactory: ifacloud {5 public IPerson Create () 6 {7 return new JapanPerson (); 8} 9}Japanese factory class 1 // <summary> 2 // Chinese factory class 3 // </summary> 4 public class ChinaFactory: ifacloud {5 public IPerson Create () 6 {7 return new ChinaPerson (); 8} 9}Factories in China

C: called on the client

1 // china 2 IFactory factory = new ChinaFactory (); 3 IPerson chinaPerson = factory. create (); 4 bool result = chinaPerson. add (new Person {5 Id = Guid. newGuid (). toString (), 6 UserName = "zs", 7 RealName = "zhangsan", 8 Nationality = Nationality. china, 9 AddDate = DateTime. now10}); 11 if (result) {12 Console. writeLine ("China added successfully"); 13} 14 15 // Japan 16 IFactory factory1 = new ChinaFactory (); 17 IPerson Japan person = factory. create (); 18 bool result1 = Japan person. add (new Person {19 Id = Guid. newGuid (). toString (), 20 UserName = "ls", 21 RealName = "", 22 Nationality = Nationality. america, 23 AddDate = DateTime. now24}); 25 if (result1) {26 Console. writeLine ("Japan successfully added"); 27}Client

D: view the effect

Advantage: people with new nationalities can be added without modifying existing businesses in line with the open and closed principles, with great flexibility.

Disadvantage: You need to create more classes (this is not counted)

The above two models can be used together in practical application to summarize the following factory models

Summary of the two factory models

Purpose:

1: The Factory method mode is a lightweight mode that achieves independence from a specific application model. The customer only uses the interface programming mode to solve other problems.

2: The factory mode has a special advantage that it can connect parallel class layers.

Use Cases:

1: flexibility is very important

2: objects can be extended by subclass

3: the customer program delegates its responsibilities to sub-classes of parallel layers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.