当然了
策略
图案是这里最合适的。
下面是完整的代码(虽然是C#),但是它应该解释实现风格
class Program
{
private static void Main(string[] args)
{
IStrategyManager manager = new StrategyManager(); // this code is added
FileInputStream fis = new FileInputStream(new File("test.xls"));
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fis);
int numberOfSheets = hssfWorkbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++)
{
HSSFSheet sh = hssfWorkbook.getSheetAt(i);
String sname = sh.getSheetName();
manager.Manage(sname); // this code is added
}
}
}
战略经理存储所有转换器
interface IStrategyManager
{
void Manage(string sheetName);
}
class StrategyManager : IStrategyManager
{
private Dictionary<string, IConverter> dictionary = new Dictionary<string, IConverter>();
public StrategyManager()
{
// store converter name & its implementation class name which are one and same
dictionary.Add("Test", new Test());
dictionary.Add("Test2", new Test2());
}
public void Manage(string sheetName)
{
dictionary[sheetName].Convert(sheetName); // magic happens here
}
}
下面是各种类型的转换器实现
interface IConverter
{
void Convert(string sheetName);
}
class Test : IConverter
{
public void Convert(string sheetName)
{
/* conversion logic for test converter goes here*/
}
}
class Test2 : IConverter
{
public void Convert(string sheetName)
{
/* conversion logic for test2 converter goes here*/
}
}
@用户3310115,希望有帮助,如果需要澄清,请联系我。谢谢