C -- using abstract method to realize simple factory design pattern

static void Main(string[] args)
{
//Implementing a simple factory design pattern with abstract classes
//Judge which brand of notebook to produce according to the user's input
Console.WriteLine("please enter the brand of notebook you want to produce");
string brand = Console.ReadLine();
//Substitute the input value into the static method to determine which notebook to produce, and then assign it to the parent class
NoteBook nb = GetNoteBook(brand);
//According to the result of input judgment, which kind of method is called to output the greeting result of production notebook
nb.SayHello();
Console.ReadKey();

    }

    //The core part of a simple factory, according to user input, creates an object assignment to the parent class
   public static NoteBook GetNoteBook(string brand)
    {
        NoteBook nb= null;
        switch (brand)
        {
            case "Lenovo":nb = new Lenovo();
                break;
            case "ACER":nb = new Acer();
                break;
            case "Dell":nb = new Dell();
                break;
            case "ASUS":nb = new ASUS();
                break;
        }
        return nb;
    }

    //At first, we didn't know what kind of notebook users wanted to produce, so we implemented it with abstract classes
    //Note: the parent method is meaningful, the virtual method
    //When the method in the parent class doesn't know how to implement it, you can consider writing the parent class as an abstract class and the method as an abstract method
    public abstract class NoteBook
    {
        public abstract void SayHello();
    }
    public class Lenovo : NoteBook
    {
        public override void SayHello()
        {
            Console.WriteLine("I am Lenovo notebook");
        }
    }
    public class Acer : NoteBook
    {
        public override void SayHello()
        {
            Console.WriteLine("I'm ACER notebook");
        }
    }
    public class Dell : NoteBook
    {
        public override void SayHello()
        {
            Console.WriteLine("I am Dell Notebook");
        }
    }
    public class ASUS : NoteBook
    {
        public override void SayHello()
        {
            Console.WriteLine("I'm ASUS notebook");
        }
    }
}

Tags: C++

Posted on Sat, 09 Nov 2019 09:46:55 -0500 by Jewbilee