我正在尝试使用工厂模式制作自定义对象。理想情况下,我希望有一些可以继承的基础对象,但specifc对象可以像基础对象一样工作,并且只能执行它可以执行的特定任务。我似乎无法通过新创建的对象访问基础对象的数据。我看了一些教程,并拼凑了我认为应该起作用但碰壁的东西。
现在,我正在通过实例化一家工厂来这样做,以便以后进行测试时更容易。我试图通过不使其抽象化来直接访问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();
答案 0 :(得分:0)
您似乎试图在错误的对象上调用该成员。
//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();
}