C # basic simple factory mode and Singleton Mode,

Source: Internet
Author: User

C # basic simple factory mode and Singleton Mode,

Design pattern: refers to the code Design experience that most people use repeatedly.

Role: code reuse, easy to understand, and ensure code reliability.

I. Simple factory Model

Usage: Create a factory class (naming convention ends with Factiory) and a static method with parameters (return different subclass objects according to different parameters.

Public class FunctionFactory

{

Public static FatherClass Function (string str)

{

FatherClass fc = null;

...

Return fc = new ChildClass ();

}

}

Main ()

{

Fc. Subclass method (); // rewrite Method

}

Ii. Singleton Mode

By creating a private constructor, you cannot instantiate an object (not new). By creating an instantiated object using a static method, you can only have one instantiated object (single instance) in a class ).

    

Namespace Singleton Mode
{
Public class Function
{
Private Function (){}// Define the private constructor
Private static Function f; // defines the private static variable of the data type.
Public static Function createtext ()
{
If (f = null)
{
F = new text (); // if f is null, the private constructor is called.
}
Return f; // return f to the caller
}

}
}

 

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.