设计模式之:工厂方法模式FactoryMethodPattern的实现
本例用到了配置文件、接口、反射、多态;
满足的设计原则:
- 通过工厂,实现创建对象和使用对象的分离,实现松耦合,满足迪米特法则;
- 通过配置文件指定创建对象类型,而不需更改源代码,满足开闭原则;
- 容易实现功能扩展,只需添加新的Logger实现类和新的Factory实现类即可,无须更改源代码,满足开闭原则;
- 面向接口编程,而不是面向具体实现类编程,满足依赖倒置原则;
- 面向接口编程,客户端实际使用的是实现类,用实现类替换接口类,满足里氏替换原则;
类图 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();
}
}
运行结果: