Recently, I watched the simple factory model. I just briefly talked about it in the video, so I checked it online and got a preliminary understanding. It has a close relationship with polymorphism, it is implemented by creating a parent class and deriving different child classes to generate different functions. It is then implemented based on the instantiated child classes specified in the main program.
Factory, I think everyone knows what the factory is doing in reality, and it produces products. As for the specifications, they don't know, so they need an abstract role to tell them what to produce, such as nut, so the parent class is generated, it is a nut, but what about the specification? At this time, you need a specific role to specify the specification, that is, the Child classes derived from the abstract class to classify different specifications. Below is a simple code description:
Using System; using System. text; class Program {static void Main (string [] args) {DVD = new dvd (); Console. writeLine (dvd. playVideo (); VCD vcd = new VCD (); Console. writeLine (vcd. playVideo (); TEST () ;}// VideoShow factory static void TEST () {// because VideoShow is the parent class of VCD and DVD, so vs can accommodate VCD and DVD VideoShow vs; // vs indicates abstract base class vs = new DVD (); Play (vs); vs = new VCD (); play (vs);} // used for polymorphism, equivalent to an interface static void Play (VideoShow vs) {string str =. playVideo (); Console. writeLine (str) ;}}// abstract role: VideoShowPublic abstract class VideoShow {public abstract string PlayVideo () ;}// two specific implementations // specific role: VCDpublic class VCD: videoShow {public override string PlayVideo () {return "My VCD" ;}}// role: DVDpublic class DVD: VideoShow {public override string PlayVideo () {return "I put a DVD ";}}
The running result is as follows:
This Code describes a simple factory model. from small to large, the first thing we need to do is to produce a DVD or VCD. These two products belong to the abstract class Videoshow, if you want to directly include Videoshow into the main program, you need to change the sub-class. This main function requires an interface for flexibility and scalability. What is the interface? That is, in the Code, vs is a specification, and both VCD and DVD comply with this specification. The use of interfaces complies with the open and closed principles, minimize the direct contact between the Code and the environment and change it to an interface. To implement the result, you only need to expand it in the main program and subclass.