Create an Ioc wheel step by step (2). Explain how to create a generic factory and an ioc Wheel

Source: Internet
Author: User

Create an Ioc wheel step by step (2). Explain how to create a generic factory and an ioc Wheel
Create an Ioc wheel directory step by step. Net core is released. Create an Ioc wheel step by step, get some. net magic, and speed near new (1)Create an Ioc wheel step by step (2) and explain how to create a generic Factory

Details about generic factories

Since I said that the Ioc container is a luxury edition factory and an automatic assembly factory, let's start with the factory, create a factory first, and then upgrade it to an Ioc container.

First, let's write the simplest abstract factory class, or the previous text message.

    public class SMSFactory    {        public static ISMS Get()        {            return new XSMS();        }    }

Then we figured out how to keep this XSMS from being written into the code. Well, we added a registration method to pass the SMS object in.

    public class SMSFactory    {        static ISMS _sms;        public static ISMS Get()        {            return _sms;        }        public static void Reg(ISMS sms)        {            _sms = sms;        }    }

This Code separates the business dependency on XSMS, but you still need to register an ISMS implementation object when the program starts, such as SMSFactory. Reg (new XSMS ());

The more complicated this factory is, the more it can only be used for text messages. Can it be universal? Well, change it to generic.

    public class Factory<T> where T:class    {        static T _obj;        public static T Get()        {            return _obj;        }        public static void Reg(T obj)        {            _obj = obj;        }    }

Well, a simple generic factory has been created. Let's think about it again. It's a little unscientific to transfer the new object when the system starts, can you make the factory new?

Public class Factory <T> where T: class, new () {public static T Get () {return new S (); // dizzy, where can I get S from?} public static void Reg <S> () where S: T {// How can I save S (inheritance class ??? This is a headache }}

It doesn't seem to work. How can we save the information of the inheritance class in this factory? A wise predecessor thought of a method to create an object containing S information, this object inherits an interface containing the Create method, and calls the Create method of this object during Get.

Public class Factory <T> where T: class {static ICreate creater; interface ICreate {T Create ();} class Creater <U>: ICreate where U: T, new () {public T Create () {return new U () ;}} public static T Get () {// calling the Create method of the creater object is actually equivalent to calling the new U () return Creater of creater <U>. create ();} public static void Reg <S> () where S: T, new () {// here, we saved the information of S to the creater object. creater = new Creater <S> ();}}

Perfect. I used a temporary object to save the information of the inheritance class, so that I could register the inheritance class in the factory class. I went back to the problem of the SMS module modified by Xiao Huang in the previous article, we can also use this generic Factory to solve the business dependency problem. var sms = Factory <ISMS>. get (); just register the implementation class in the startup configuration

Can we extend it to support Singleton? Of course, the answer is yes. Just rebuild Creater.

Public class Factory <T> where T: class {static ICreate creater; interface ICreate {T Create ();} class Creater <U>: ICreate where U: T, new () {public T Create () {return new U () ;}} class SingletonCreater <U>: ICreate where U: T, new () {T instance; object locker = new object (); public T Create () {// use the double check lock if (instance = null) {lock (locker) {if (instance = null) {Interlocked. exchange (ref instance, new U () ;}} return instance ;}} public static T Get () {return creater. create ();} public static void Reg <S> () where S: T, new () {creater = new Creater <S> ();} public static void RegSingleton <S> () where S: T, new () {creater = new SingletonCreater <S> ();}}

Yo, really, but there is a lock. Can you remove the lock? yes, we will use the static readonly magic to create an internal class. This object will be created only when this internal class is accessed, it is thread-safe.

    public class Factory<T> where T : class    {        static ICreate creater;        interface ICreate        {            T Create();        }        class Creater<U> : ICreate where U : T, new()        {            public T Create()            {                return new U();            }        }        class SingletonCreater<U> : ICreate where U : T, new()        {            class InstanceClass            {                public static readonly T Instance = new U();            }            public T Create()            {                return InstanceClass.Instance;            }        }        public static T Get()        {            return creater.Create();        }        public static void Reg<S>() where S : T, new()        {            creater = new Creater<S>();        }        public static void RegSingleton<S>() where S : T, new()        {            creater = new SingletonCreater<S>();        }    }

Sure enough, black magic. Next we will try again to modify this generic factory so that it can support the input of parameters. In fact, it is also very easy to use a dictionary to save the correspondence between the key and creater.

Public class Factory <T> where T: class {interface ICreate {T Create ();} class Creater <U>: ICreate where U: T, new () {public T Create () {return new U () ;}} class SingletonCreater <U>: ICreate where U: T, new () {class InstanceClass {public static readonly T Instance = new U ();} public T Create () {return InstanceClass. instance ;}# static ICreate creater without parameters in region; public static T Get () {return creater. create ();} public static void Reg <S> () where S: T, new () {creater = new Creater <S> ();} public static void RegSingleton <S> () where S: T, new () {creater = new SingletonCreater <S> ();} # endregion # static IDictionary with parameters for region <string, ICreate> creaters = new System. collections. concurrent. concurrentDictionary <string, ICreate> (); public static T Get (string key) {ICreate ct; if (creaters. tryGetValue (key, out ct) return ct. create (); throw new Exception ("not registered");} public static void Reg <S> (string key) where S: T, new () {creaters [key] = new Creater <S> ();} public static void RegSingleton <S> (string key) where S: T, new () {creaters [key] = new SingletonCreater <S> () ;}# endregion}

All right, the generic factory details and magic modification are complete. You can register a singleton and test it. It's perfect. Is it already known as Ioc? Next, let's try it again, transformed to reading from configuration and optimizing the performance obtained from Parameters

 

 

I don't want to cause war, but it's really generic. net magic, java does not work, java can only reflect, close to new performance is. net

 

Code download: written in VS2015 update3. You can directly copy the code without using. net core.

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.