我试图使用工厂模式来定制一个对象。理想情况下,我希望有一些可以继承的基本对象,但是指定的对象可以像基本对象那样工作,也可以只执行特定的任务。我似乎无法通过新创建的对象访问基本对象的数据。我已经看了一些教程,拼凑出我认为应该有效的东西,但却碰壁了。
现在,我正在通过实例化一个工厂来实现这一点,以便以后更容易进行测试。我试图直接访问FilterPanel,方法是不使其抽象,但我不确定这是一个好的编码实践。
为什么我无法访问FilterPanel函数?
FilterPanel
public abstract class FilterPanel {
//Do generic stuff that all filters can do.
public void ClickFilterButtons(){...}
}FilterFactory
public class FilterFactory {
public FilterPanel CreateFilterPanel(string filterType) {
FilterPanel filterPanel;
switch (filterType) {
case "invoice":
filterPanel = new InvoiceFilter();
break;
case "payment":
filterPanel = new PaymentFilter();
break;
default:
throw new Exception("wrong filter!");
break;
}
return filterPanel;
}
}
public class InvoiceFilter : FilterPanel {
//Do specific stuff only Invoice filter can do.
public void InvoiceStuff(){...}
}
public class PaymentFilter : FilterPanel {
//Do specific stuff only payment filter can do.
public void PaymentStuff(){...}
}TestFile
[Test]
FilterFactory filter = new FilterFactory();
filter.CreateFilterPanel("invoice");
//Cannot access this function in the base filter class functions.
filter.ClickFilterButtons();发布于 2018-07-03 21:31:36
您似乎试图在错误的对象上调用成员。
//Create the factory
FilterFactory factory = new FilterFactory();
//Create the filter using the factory
FilterPanel filter = factory.CreateFilterPanel("invoice");
//Call the public member on the returned filter
filter.ClickFilterButtons();
//To access InvoiceFilter specific stuff you need to cast
if(filter is InvoiceFilter) {
(filter as InvoiceFilter).InvoiceStuff();
}https://stackoverflow.com/questions/51162182
复制相似问题