I. Overview
In software systems, the creation of "an object" is often faced. due to changes in requirements, the specific implementation of this object is often subject to drastic changes, however, it has relatively stable interfaces. How to deal with this change? How can we provide a plug-in mechanism to isolate the changes of "this variable object", so as to keep the "other objects dependent on this object" in the system from changing as required? The factory method mode can be used.
Ii. Factory method mode
The factory method mode defines an interface for creating objects, so that its subclass determines which object to instantiate. Delay the creation of an object to its subclass.
The structure of the factory method mode is as follows:
Product defines the interface of the object created by the factory method.
Concreteproduct implements the product interface and defines specific objects.
Creator defines the factory method for creating a specific object. This method returns an object of the product type. Creator can also define the default implementation of a factory method, which returns a default concreteproduct object
Concretecreator implements the Creator interface. The factory method is redefined to return a concreteproduct instance.
Iii. Example
Let's look at the application of the factory method model by implementing a document processing system.
First, define the document type interface and two specific document types.
1 public interface IFile 2 { 3 void New(); 4 void Save(); 5 } 6 public class DocFile : IFile 7 { 8 public void New() 9 {10 Console.WriteLine("New Doc Create");11 }12 public void Save()13 {14 Console.WriteLine("Save Doc");15 }16 }17 public class TxtFile : IFile18 {19 public void New()20 {21 Console.WriteLine("New Txt Create");22 }23 public void Save()24 {25 Console.WriteLine("Save Txt");26 }27 }
Copy code
Then implement the factory method for object creation and create factory for specific documents
1 interface IFileFactory 2 { 3 IFile Create(); 4 } 5 public class DocFileFactory : IFileFactory 6 { 7 public IFile Create() 8 { 9 return new DocFile();10 }11 }12 public class TxtFileFactory : IFileFactory13 {14 public IFile Create()15 {16 return new TxtFile();17 }18 }
Copy code
Finally, let's take a look at how to call
1 static void Main(string[] args) 2 { 3 IFile docFile = (new DocFileFactory()).Create(); 4 docFile.New(); 5 docFile.Save(); 6 IFile txtFile = (new TxtFileFactory()).Create(); 7 txtFile.New(); 8 txtFile.Save(); 9 Console.ReadLine();10 }