标签:工厂模式工厂方法模式 工厂方法模式
在阎宏博士的《JAVA与模式》一书中开头是这样描述工厂方法模式的:public interface ExportFactory {
public ExportFile factory(String type);
} 具体工厂角色类源代码:public class ExportHtmlFactory implements ExportFactory{
@Override
public ExportFile factory(String type) {
// TODO Auto-generated method stub
if("standard".equals(type)){
return new ExportStandardHtmlFile();
}else if("financial".equals(type)){
return new ExportFinancialHtmlFile();
}else{
throw new RuntimeException("没有找到对象");
}
}
}
public class ExportPdfFactory implements ExportFactory {
@Override
public ExportFile factory(String type) {
// TODO Auto-generated method stub
if("standard".equals(type)){
return new ExportStandardPdfFile();
}else if("financial".equals(type)){
return new ExportFinancialPdfFile();
}else{
throw new RuntimeException("没有找到对象");
}
}
}public interface ExportFile {
public boolean export(String data);
} 具体导出角色类源代码,通常情况下这个类会有复杂的业务逻辑。public class ExportFinancialHtmlFile implements ExportFile{
@Override
public boolean export(String data) {
// TODO Auto-generated method stub
/**
* 业务逻辑
*/
System.out.println("导出财务版HTML文件");
return true;
}
}public class ExportFinancialPdfFile implements ExportFile{
@Override
public boolean export(String data) {
// TODO Auto-generated method stub
/**
* 业务逻辑
*/
System.out.println("导出财务版PDF文件");
return true;
}
}public class ExportStandardHtmlFile implements ExportFile{
@Override
public boolean export(String data) {
// TODO Auto-generated method stub
/**
* 业务逻辑
*/
System.out.println("导出标准HTML文件");
return true;
}
}public class ExportStandardPdfFile implements ExportFile {
@Override
public boolean export(String data) {
// TODO Auto-generated method stub
/**
* 业务逻辑
*/
System.out.println("导出标准PDF文件");
return true;
}
}
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String data = "";
ExportFactory exportFactory = new ExportHtmlFactory();
ExportFile ef = exportFactory.factory("financial");
ef.export(data);
}
}标签:工厂模式工厂方法模式 工厂方法模式
原文地址:http://blog.csdn.net/itjavawfc/article/details/44834725