C # design mode (2)--Simple Factory mode (Factory)

Source: Internet
Author: User

We create different objects with Factory.

For example, if you create an interface for a car, create an object that implements the interface through the Factory factory, and create different objects based on our choices.

Create a car interface

    /// <summary>    /// Simple Factory mode     /// </summary>     Public Interface Iautocarmake    {        //<summary>        /// Create a        car /// </summary>        void Createautocar ();    }

Create two derived classes, respectively, to create two types of cars with different colors

    /// <summary>    ///Red Car/// </summary>     Public class_redcar:iautocarmake { Public voidCreateautocar () {Console.WriteLine ("Create a red car"); }    }    /// <summary>    ///Blue Car/// </summary>     Public class_bluecar:iautocarmake { Public voidCreateautocar () {Console.WriteLine ("Create a blue car"); }    }

Generating different object instances from the factory class

    /// <summary>    ///Simple Factory mode-factory class/// </summary>     Public classFactory { PublicIautocarmake Createautocar (stringflag) {            Switch(flag) { Case "Red":                    return New_redcar ();  Case "Blue":                    return New_bluecar (); }            return NULL; }        Static voidMain (string[] args) {Iautocarmake Parents=NewFactory (). Createautocar ("Red"); Iautocarmake Parents=NewFactory (). Createautocar ("Blue"); Parents.            Createautocar ();        Console.readkey (); }    }

C # design mode (2)--Simple Factory mode (Factory)

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.