我在这里链接类构造函数的动机是为了让我的应用程序有一个主流使用的默认构造函数,以及第二个允许我注入mock和stub的默认构造函数。
它只是在":this(...)“中看起来有点丑陋的”新“东西。从默认构造函数调用参数化构造函数,我想知道其他人会在这里做什么?
(仅供参考-> SystemWrapper)
using SystemWrapper;
public class MyDirectoryWorker{
// SystemWrapper interface allows for stub of sealed .Net class.
private IDirectoryInfoWrap dirInf;
private FileSystemWatcher watcher;
public MyDirectoryWorker()
: this(
new DirectoryInfoWrap(new DirectoryInfo(MyDirPath)),
new FileSystemWatcher()) { }
public MyDirectoryWorker(IDirectoryInfoWrap dirInf, FileSystemWatcher watcher)
{
this.dirInf = dirInf;
if(!dirInf.Exists){
dirInf.Create();
}
this.watcher = watcher;
watcher.Path = dirInf.FullName;
watcher.NotifyFilter = NotifyFilters.FileName;
watcher.Created += new FileSystemEventHandler(watcher_Created);
watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
watcher.EnableRaisingEvents = true;
}
public static string MyDirPath{get{return Settings.Default.MyDefaultDirPath;}}
// etc...
}发布于 2010-03-24 08:21:00
包含默认构造函数是一种代码味道,因为现在该类被耦合到IDirectoryInfoWrap的具体实现。为了使您的工作更轻松,可以使用类外部的IOC容器来注入不同的依赖项,具体取决于您运行的是测试代码还是主流应用程序。
发布于 2010-03-24 07:55:14
我就是这么做的。
class MyUnitTestableClass
{
public MyUnitTestableClass(IMockable foo)
{
// do stuff
}
public MyUnitTestableClass()
: this(new DefaultImplementation())
{
}
}https://stackoverflow.com/questions/2504466
复制相似问题