2012年10月1日 星期一

c# use factory mode (工廠模式)

Usage:

//Use printer1 
ITest it = Factory.create(1);
            Console.WriteLine( it.iText()); // to print text
            Console.WriteLine( ((Printer1)it).autoInputPaper()); // and input a paper automatically

Code:

interface ITest
    {
        string iText();
    }
class Printer1 : ITest
    {
        #region ITest Members

        public string iText()
        {
            // TODO:  Add Test.printText implementation
            return ("Printer1 prints string...");
        }

        public string autoInputPaper()
        {
            // TODO:  Add Test.printText implementation
            return ("Printer1 inputs a paper automatically...");
        }

        #endregion

    }

    class Printer2 : ITest
    {
        #region ITest Members
        public string tt = "";

        public string iText()
        {
            // TODO:  Add Test.printText implementation
            return ("Printer2 prints string...");
        }

        #endregion

    }

    class Factory
    {
        public static ITest create(int itype)
        {
            if (itype == 1)
            {
                return new Printer1();
            }
            else
            {
                return new Printer2();
            }
        }

    }

沒有留言: