Abstract Factory Learning

Source: Internet
Author: User

1. Define an interface: human, which can run such an action (probably so)

 public interface IHuman    {        void Run();    }

2. Come to a man and a woman to let them inherit from humans. Of course, you have to implement the run () method.

public class Woman : IHuman    {        public Woman()        {            Console.WriteLine("The girl fall in love");        }        public void Run()        {            Console.WriteLine("There is a girl in the running");        }    }    public class Man : IHuman    {        public Man()        {            Console.WriteLine("The guy fall in love");        }        public void Run()        {            Console.WriteLine("A guy with the girl behind");        }    }

3. The following is a processing factory template.

Public interface ifacloud {// <summary> // declare a getmarried to return the ihuman instance /// </Summary> /// <returns> return the ihuman instance </returns> ihuman getmarried ();} public class womanfactory: ifacloud {public ihuman getmarried () {return New Woman () ;}} public class manfactory: ifacloud {public ihuman getmarried () {return New Man ();}}

4. Write a method to generate the corresponding processing factory

Public class humanfactory {public static ifacloud createfacory (string factorytype) {type T = type. getType (factorytype); Return activator. createinstance (T) as ifacloud; // another method is used to create an object factory object assembly. load (Assembly name ). createinstance (namespace. class Name) // ifactory carfactory = system. reflection. assembly. load ("leleapplication1 "). createinstance (factorytype) as ifacloud; // return carfactory ;}}

5. test:

Class program {static void main (string [] ARGs) {# region demo1 // leleapplication1.manfactory can be written to the configuration file. Here, ifactory humfactory = humanfactory. createfacory ("leleapplication1.manfactory"); ihuman Hyman = humfactory. getmarried (); Hyman. run (); console. readkey (); # endregion }}

Effect:

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.