一个工厂类只创建一个产品
定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。
将所要创建的具体对象放在子类, 实现扩展(非更改)
简单工厂实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| interface ILogger{ public void WriteLog(); }
class DatabaseLogger : ILogger{ public void WriteLog(){ } } class FileLogger : ILogger{ public void WriteLog(){ } }
class LoggerFactory{ public static Logger CreateLogger(string args){ if(args.EqualsIgnoreCase("db")){ ILogger logger = new DatabaseLogger(); return logger; } else if(args.EqualsIgnoreCase("file")){ ILogger logger = new FileLogger(); return logger; } else return null; } }
|
缺点
新增产品必须修改工厂类, 违反开闭原则;
所有产品都由同一工厂创建,职责重,逻辑复杂,耦合度高
工厂方法把简单工厂的内部逻辑判断移到了客户端代码来进行
工厂方法
定义一个用于创建对象的接口, 让子类决定实例化哪个类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| interface ILogger{ public void WriteLog(); } class DatabaseLogger : ILogger{ public void WriteLog(){ } } class FileLogger : ILogger{ public void WriteLog(){ } }
interface ILoggerFactory{ public ILogger CreateLogger(); } class DatabaseLoggerFactory : ILoggerFactory{ public ILogger CreateLogger(){ Logger logger = new DatabaseLogger(); return logger; } } class FileLoggerFactory : ILoggerFactory{ public ILogger CreateLogger(){ Logger logger = new FileLogger(); return logger; } }
class Client{ ILoggerFactory factory; ILogger logger; factory = new FileLoggerFactory(); logger = factory.CreateLogger(); logger.WriteLog(); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| interface ILogger{ public void WriteLog(); }
class DatabaseLogger : ILogger{ public void WriteLog(){ } } class FileLogger : ILogger{ public void WriteLog(){ } }
class Logger(ILogger logger){ private logger; public Logger(ILogger logger){ this.logger = logger; } public void WriteLog(){ logger.WriteLog(); } }
class Client{ var logger = Logger(new DatabaseLogger()); logger.WriteLog(); }
|