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