. NET's simple factory model

Source: Internet
Author: User

Abstract a method of producing pens

Namespace Simplefactory
{
Public abstract class Abstractpen
{
public abstract void Creatpen ();
}
}

Inherit the method of producing pen to produce various pens

Namespace Simplefactory
{
public class Gangbi:abstractpen
{
public override void Creatpen ()
{
Console.WriteLine ("Production pen ... ");
}
}
public class Qianbi:abstractpen
{
public override void Creatpen ()
{
Console.WriteLine ("Production pencil ... ");
}
}
public class Shuibi:abstractpen
{
public override void Creatpen ()
{
Console.WriteLine ("Production fountain pen ... ");
}
}

}

In the factory select the type that needs to be produced, you need to return an abstract type of pen, judging by that type

Namespace Simplefactory
{
public class Factory
{
public static Abstractpen pen (string pentype) {
Abstractpen p = null;
if (Pentype = = "Pencil") {
p = new Qianbi ();
} else if (Pentype = = "Pen") {
p = new Gangbi ();
} else if (Pentype = = "Fountain pen")
{
p = new Shuibi ();
}
return p;
}
}
}

To output the required things, you need to create an abstract pen object, get the objects returned from the top of the factory, and use the object to produce

static void Main (string[] args)
{
Console.Write ("Please enter the pen to be produced:");
String Pen=console.readline ();
Try
{
Abstractpen p = factory.pen (pen);
if (p!=null) {
P.creatpen ();
}
}
catch (Exception e)
{
Console.WriteLine ("Input Error" +e.message);
}


Console.ReadLine ();
}

. NET's simple factory model

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.