Design Patterns: Singleton and Simple Factory

Source: Internet
Author: User

Singleton design pattern: Instantiate only one Class object!

1  Public class Person2     {3        //1: First define a static variable4        //2: Privatize the constructor of this class5        //3: Define a static method that assigns the class object to this static variable6        //4: Use class in other classes. Method name to invoke the object7         Public StaticPerson p1;8        PrivatePerson ()9        {Ten        } One         Public StaticPerson Get () A        { -            if(P1 = =NULL) -            { theP1 =NewPerson (); -            } -            returnP1; -        } +     } - class Program +     { A         Static voidMain (string[] args) at         { -person P1 =person.get (); -         } -}

Design Pattern II: Simple Factory

Defines a factory class that can return instances of different classes depending on the parameters, and the instances that are created usually have a common parent class.

1: Define a parent class

 Public Abstract class person    {       publicabstractvoid  Say ();         Public Person ()       {       }    }

2: Definition of two sub-classes

1     classFather:person2     {3          Public Override voidSay ()4         {5Console.WriteLine ("I'm a dad .");6         }7     }8  classSon:person9     {Ten          Public Override voidSay () One         { AConsole.WriteLine ("I'm a son ."); -         } -}

3: Define Simple factory class

1   Public Abstract classTool2     {3         Public StaticPerson St (stringtype)4        {5Person p1=NULL;6            Switch(type)7            {8                 Case"dad":9p1=NewFather ();Ten                     Break; One                 Case "son": AP1 =NewSon (); -                     Break; -  the  -  -            } -            returnP1; +  -        } +}

Design Patterns: Singleton and Simple 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.