简单工厂实例讲解

简单工厂模式:其作用是实例化对象而不需要客户了解这个对象属于那个具体的子类。
下面是一个简单工厂模式的一个Demo:

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace Factory
{
    public class Class1
    {
        static void Main(string[] args)
        {
            Log log=CretLog.CreateLogFactory();
            log.WriteLog();
        }
    }
    public interface Log
    {
        void WriteLog();
    }
    public class FileLog:Log
    {
        #region Log 成员

        public void WriteLog()
        {
            Console.WriteLine("Write FileLog Success!");
        }

        #endregion
    }

    public class EventLog:Log
    {
        #region Log 成员

        public void WriteLog()
        {
            Console.WriteLine("Write EventLog Success!");
        }

        #endregion
    }

    public class CretLog
    {
        public static Log CreateLogFactory()
        {
            string logType = System.Configuration.ConfigurationManager.AppSettings["type"];
            Log log = null;
            switch (logType.ToLower())
            {
                case "filelog":
                    log = new FileLog();
                    break;
                case "eventlog":
                    log = new EventLog();
                    break;
            }
            return log;
        }
    }
}

posted @ 2007-11-13 22:56  黑羽飘舞  阅读(290)  评论(0编辑  收藏  举报