工厂方法模式
定义一个用于创建对象的接口,让子类决定实例化哪一个类
类创建型模式 工厂父类负责定义创建产品对象的公共接口,工厂子类负责生成具体的产品对象
模式结构图
Product:定义产品的接口
ConcreteProduct:实现抽象产品接口
Factory:抽象工厂 声明一个工厂方法
ConcreteFactory:返回一个具体产品类的实例
示例:日志记录器
//Logger
interface Logger
{
void WriteLog();
}
//FileLogger
class FileLogger : Logger
{
public void WriteLog()
{
Console.WriteLine("File");
}
}
//DataBaseLogger
class DataBaseLogger : Logger
{
public void WriteLog()
{
Console.WriteLine("DataBase");
}
}
//LoggerFactory
interface LoggerFactory
{
//工厂方法的重载
Logger CreateLogger();
Logger CreateLogger(string args);
Logger CreateLogger(object obj);
}
//DatabaseLoggerFactory
class DatabaseLoggerFactory : LoggerFactory
{
public Logger CreateLogger()
{
//连接数据库 代码省略
Logger logger = new DataBaseLogger();
//初始化日志记录器 代码省略
return logger;
}
public Logger CreateLogger(string args)
{
throw new NotImplementedException();
}
public Logger CreateLogger(object obj)
{
throw new NotImplementedException();
}
}
//FileLoggerFactory
class FileLoggerFactory : LoggerFactory
{
public Logger CreateLogger()
{
Logger logger = new FileLogger();
//创建文件 代码省略
return logger;
}
public Logger CreateLogger(string args)
{
throw new NotImplementedException();
}
public Logger CreateLogger(object obj)
{
throw new NotImplementedException();
}
}
//client
LoggerFactory factory;
Logger logger;
//读取配置文件
string factoryType = ConfigurationManager.AppSettings["factory"];
//反射生成对象
factory = (LoggerFactory)Assembly.Load("FactoryMethod").CreateInstance(factoryType);
logger = factory.CreateLogger();
logger.WriteLog();