gpt4 book ai didi

c# - 如何防止工厂方法模式在构造函数中引起有关虚拟成员调用的警告?

转载 作者:太空狗 更新时间:2023-10-29 19:43:00 25 4
gpt4 key购买 nike

关于 www.dofactory.com我找到了工厂模式的真实示例。但是代码会在 ReSharper 中生成有关构造函数中的虚拟成员调用的警告。

引起警告的代码如下:

abstract class Document
{
private List<Page> _pages = new List<Page>();

// Constructor calls abstract Factory method
public Document()
{
this.CreatePages(); // <= this line is causing the warning
}

public List<Page> Pages
{
get { return _pages; }
}

// Factory Method
public abstract void CreatePages();
}

class Resume : Document
{
// Factory Method implementation
public override void CreatePages()
{
Pages.Add(new SkillsPage());
Pages.Add(new EducationPage());
Pages.Add(new ExperiencePage());
}
}

在消费代码中,您可以简单地使用:

Document document = new Resume();

我确实理解为什么在构造函数中调用虚拟成员是个坏主意(如 here 所述)。

我的问题是如何重构它以便仍然使用工厂模式,但在构造函数中不调用虚拟成员。

如果我只是从构造函数中删除对 CreatePages 的调用,消费者将不得不显式调用 CreatePages 方法:

Document document = new Resume();
document.CreatePages();

我更喜欢这样的情况,即创建一个新的 Resume 就是实际创建一个包含页面的 Resume 所需要的。

最佳答案

重构它的一种方法是预先传递页面,并将它们传递给 protected 构造函数:

public abstract class Document {
protected Document(IEnumerable<Page> pages) {
// If it's OK to add to _pages, do not use AsReadOnly
_pages = pages.ToList().AsReadOnly();
}
// ...
}

public class Resume : Document {
public Resume() : base(CreatePages()) {
}
private static IEnumerable<Page> CreatePages() {
return new Page[] {
new SkillsPage(),
new EducationPage(),
new ExperiencePage()
};
}
}

附言我不确定这与工厂方法有什么关系。您的帖子说明了 Template Method Pattern .

关于c# - 如何防止工厂方法模式在构造函数中引起有关虚拟成员调用的警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11269054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com