使用工厂模式,根据不同的输入格式创建不同的对象,并对每个对象进行相应的操作。
示例代码:
interface Formatter { formatData(): string; }
class CsvFormatter implements Formatter { constructor(private data: any) {}
formatData(): string { let csv = ''; for (const row of this.data) { csv += Object.values(row).join(',') + '\n'; } return csv; } }
class JsonFormatter implements Formatter { constructor(private data: any) {}
formatData(): string { return JSON.stringify(this.data); } }
class XmlFormatter implements Formatter { constructor(private data: any) {}
formatData(): string {
let xml = '\n';
for (const row of this.data) {
xml +=
;
for (const [key, value] of Object.entries(row)) {
xml += <${key}>${value}${key}>\n
;
}
xml += \n
;
}
xml += '\n';
return xml;
}
}
class FormatterFactory {
static createFormatter(format: string, data: any): Formatter {
switch (format) {
case 'csv':
return new CsvFormatter(data);
case 'json':
return new JsonFormatter(data);
case 'xml':
return new XmlFormatter(data);
default:
throw new Error(Unsupported format: ${format}
);
}
}
}
const data = [ { name: 'Alice', age: 30, gender: 'female' }, { name: 'Bob', age: 40, gender: 'male' }, { name: 'Charlie', age: 50, gender: 'male' }, ];
const formatter = FormatterFactory.createFormatter('xml', data); const formattedData = formatter.formatData(); console.log(formattedData);