其他分享
首页 > 其他分享> > 设计模式之:工厂方法模式FactoryMethodPattern的实现

设计模式之:工厂方法模式FactoryMethodPattern的实现

作者:互联网

本例用到了配置文件、接口、反射、多态;

满足的设计原则:

类图 with StarUML

Logger接口及其实现类:

/// <summary>
    /// LLogger接口
    /// </summary>
    internal interface Logger
    {
        void WriteLog();
    }
    internal class FileLogger : Logger
    {
        public void WriteLog()
        {
            Console.WriteLine("文件日志记录");
        }
    }
    internal class DatabaseLogger : Logger
    {
        public void WriteLog()
        {
            Console.WriteLine("数据库日志记录");
        }
    }

Factory接口及其实现类:

    internal interface LoggerFactory
    {
        Logger CreateLogger();
    }
    internal class FileLoggerFactory : LoggerFactory
    {
        public Logger CreateLogger()
        {
            return new FileLogger();
        }
    }
    internal class DatabaseLoggerFactory : LoggerFactory
    {
        public Logger CreateLogger()
        {
            return new DatabaseLogger();
        }
    }

配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<appSettings>
		<add key="factoryType" value="FactoryMethodPattern.DatabaseLoggerFactory"/>
	</appSettings>
</configuration>

客户端:

    internal class Program
    {
        static void Main(string[] args)
        {
            LoggerFactory factory;
            Logger logger;
            //读取配置文件
            string factoryType = ConfigurationManager.AppSettings["factoryType"];
            //用反射创建对象
            factory = Assembly.Load("FactoryMethodPattern").CreateInstance(factoryType) as LoggerFactory;
            logger = factory.CreateLogger();
            logger.WriteLog();
            Console.Read();
        }
    }

 

运行结果:

标签:LoggerFactory,实现,FactoryMethodPattern,接口,工厂,internal,Logger,设计模式,class
来源: https://www.cnblogs.com/zhangdezhang/p/16091671.html