C#抽象工廠方法

1.創建一個工廠類,定義工廠中的方法
    public interface Factory
    {
        String text1(String text);
        String text2(String text);
    }

2.創建兩個類Class1和Class2,繼承工廠類,實現工廠類中的方法,進行不同的操作
    public class Class1:Factory
    {
        public String text1(String text)
        {
            return "class1-text1-" + text;
        }
        public String text2(String text)
        {
            return "class1-text2-" + text;
        }
    }
    public class Class2:Factory
    {
        public String text1(String text)
        {
            return "class2-text1-" + text;
        }
        public String text2(String text)
        {
            return "class2-text2-" + text;
        }
    }

3.創建工廠實現類,利用放射的機制實例化所需要的工廠對象
    public class DBFactory
    {
        public Factory getFacory(string name)
        {
            Factory factory=null;
            try
            {
                System.Type type = System.Type.GetType(name, true);
                factory = (Factory)Activator.CreateInstance(type);
            }
            catch (Exception e)
            {
            }
            return factory;
        }
    }

4.客戶代碼
   String name = "Factory.Class2";
   DBFactory dbfactory = new DBFactory();
   Factory.Factory factory = dbfactory.getFacory(name);
   Console.WriteLine(factory.text1("123"));

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章