需求描述:
某软件公司欲开发一个数据格式转换工具,可以将不同数据源如txt文件、数据库、Excel表格中的数据转换成XML格式。为了让系统具有更好的扩展性,在未来支持新类型的数据源,开发人员使用工厂方法模式设计该转换工具的核心类,客户端只需使用工厂类即可获得具体的转换类对象,再调用其相应方法实现数据转换操作。绘制该类图,并选择一种语言编程实现。
在idea中生成UML类图
具体代码:
//转换接口
public interface ConvertFactory {
Convertor getConvertor();
}
// 产品接口
public interface Convertor {
void transform();
}
//具体转换工厂
public class ConcreteConvertFactory {
}
class DBConvertorFactory implements ConvertFactory{
@Override
public Convertor getConvertor() {
System.out.println("DataBase转换工厂Complete");
return new DBConvertor();
}
}
class EXCELConvertorFactory implements ConvertFactory{
@Override
public Convertor getConvertor() {
System.out.println("EXCEL转换工厂Complete");
return new EXCELConvertor();
}
}
class TXTConvertorFactory implements ConvertFactory{
@Override
public Convertor getConvertor() {
System.out.println("TXT转换工厂Complete");
return new TXTConvertor();
}
}
//具体转换产品
public class ConcreteConvertor {
}
class DBConvertor implements Convertor{
@Override
public void transform() {
System.out.println("DB-->XML");
}
}
class EXCELConvertor implements Convertor{
@Override
public void transform() {
System.out.println("EXCEL-->XML");
}
}
class TXTConvertor implements Convertor{
@Override
public void transform() {
System.out.println("TXT-->XML");
}
}
测试代码:
public class Client {
public static void main(String[] args) {
ConvertFactory dbConvertFactory = new DBConvertorFactory();
Convertor dbConvertor = dbConvertFactory.getConvertor();
dbConvertor.transform();
ConvertFactory excelConvertorFactory = new EXCELConvertorFactory();
Convertor excelConvertor = excelConvertorFactory.getConvertor();
excelConvertor.transform();
ConvertFactory txtConvertorFactory = new TXTConvertorFactory();
Convertor txtConvertor = txtConvertorFactory.getConvertor();
txtConvertor.transform();
}
}
结果: