工厂模式
工厂方法模式是类的创建模式,又叫做虚拟构造子模式或者多态性工厂模式。
工厂方法模式的用意是定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类中。
简单地说,就是简单工厂模式的进化版,我们在上一章博客写到的玩具厂例子,在这里依旧可以用,我们假设,在生产洋娃娃和小汽车的时候,还要分为劣质的和精致的玩具,那如果你还放在一个玩具厂里面生产的话,那么你就得生产四种不同的型号了,那未免太过臃肿了,于是,我们对玩具厂再进行抽象,假设有两个玩具厂,一个生产劣质的玩具,一个生产精致的玩具,而这个厂的上面是一个玩具生产有限公司,公司董事长说,我们要建这样的两个工厂,一个命令发下来,马上盖了两个具体的玩具厂,而这两个玩具厂则分别生产劣质的和精致的,然后,董事长可以说我要生产一批精致的洋娃娃,那么你就先去找生产精致玩具的工厂,然后在这个既可以生产洋娃娃又可以生产小汽车的工厂里,传下命令,你要生产洋娃娃,然后一批具体的洋娃娃就这样出现了!这就是工厂模式!
下面是代码,这里用的例子是导出文件,作为公司的文件类型,有html,pdf三种模式,而又有两种格式,一个是标准模式,一个是财务报表模式,而我们要做的就是用工厂模式来表示;
核心类:抽象工厂类;
package Factory;
public interface ExportFactory {
public ExportFile factory(String type);
}
具体工厂类;
package Factory;
public class ExportHtmlFactory implements ExportFactory{
public ExportHtmlFactory() {
// TODO Auto-generated constructor stub
}
@Override
public ExportFile factory(String type){
if("standard".equals(type)){
return new ExportStandardHtmlFile();
}
else if("financial".equals(type)){
return new ExportFinancialHtmlFile();
}
else{
throw new RuntimeException("没有找到对象");
}
}
}
具体工厂类;
package Factory;
public class ExportPdfFactory implements ExportFactory{
@Override
public ExportFile factory(String type){
if("standard".equals(type)){
return new ExportStandardPdfFile();
}
else if("financial".equals(type)){
return new ExportFinancialPdfFile();
}
else {
throw new RuntimeException("没有找到对象");
}
}
}
下面是具体类的接口;
package Factory;
public interface ExportFile {
public boolean export(String data);
}
具体实现类;
package Factory;
public class ExportFinancialHtmlFile implements ExportFile{
public ExportFinancialHtmlFile() {
// TODO Auto-generated constructor stub
}
@Override
public boolean export(String data){
System.out.println("导出财务版html文件");
return true;
}
}
具体实现类;
package Factory;
public class ExportFinancialPdfFile implements ExportFile{
public ExportFinancialPdfFile() {
// TODO Auto-generated constructor stub
}
@Override
public boolean export(String data){
System.out.println("导出财务版PDF文件");
return true;
}
}
具体实现类;
package Factory;
public class ExportStandardHtmlFile implements ExportFile{
public ExportStandardHtmlFile() {
// TODO Auto-generated constructor stub
}
@Override
public boolean export(String data){
System.out.println("导出标准HTML文件");
return true;
}
}
具体实现类;
package Factory;
public class ExportStandardPdfFile implements ExportFile{
public ExportStandardPdfFile() {
// TODO Auto-generated constructor stub
}
@Override
public boolean export(String data){
System.out.println("导出标准PDF文件");
return true;
}
}
这就是我对工厂模式的理解
浙公网安备 33010602011771号