Simple factory and factory model in factory Mode
Factory mode definition: instantiate an object and use the factory method instead of the new operation.
Interface (IBase):
public interface IBase{ void Excute();}
Implementation Class A (BaseAImpl ):
Public class BaseAImpl: IBase {public void Excute () {Type type = this. getType (); Console. writeLine ("Class A Name: {0}, Class Name: {1}, whether to implement the interface IBase: {2}", type. fullName, type. name, typeof (IBase ). isAssignableFrom (type ));}}
Implementation Class B (BaseBImpl ):
Public class BaseBImpl: IBase {public void Excute () {Type type = this. getType (); Console. writeLine ("Class B Full name: {0}, Class Name: {1}, whether to implement interface IBase: {2}", type. fullName, type. name, typeof (IBase ). isAssignableFrom (type ));}}
Class C (BaseC): (Special Class for difference)
Public class BaseC {public void Excute () {Type type = this. getType (); Console. writeLine ("Class A Name: {0}, Class Name: {1}, whether to implement the interface IBase: {2}", type. fullName, type. name, typeof (IBase ). isAssignableFrom (type ));}}
Factory ):
/// <Summary> /// Factory class /// </summary> public class Factory {// <summary> // Factory method (where the instance is created, what do you need) /// </summary> /// <param name = "fullName"> type full name </param> /// <returns> implement IBase Instance Object </returns> public IBase CreateBase (string fullName) {// obtain all types of Type [] types = this. getType (). assembly. getTypes (); // traverse all types and search for foreach (Type type in types) {// determine whether all types are named and whether the IBase interface if (type. fullName = fullName & typeof (IBase ). isAssignableFrom (type) return Activator. createInstance (type) as IBase;} return null ;}}
Demo result:
Class Program {static void Main (string [] args) {Factory factory = new Factory (); IBase instanceA = factory. createBase (typeof (BaseAImpl ). fullName); IBase instanceB = factory. createBase (typeof (BaseBImpl ). fullName); IBase instanceC = factory. createBase (typeof (BaseC ). fullName); // special example for distinguishing instanceA. excute (); instanceB. excute (); if (instanceC = null) {Console. writeLine ("Class C: {0} has not implemented the interface IBase", typeof (BaseC ). fullName);} Console. readLine ();}}