创造型-工厂模式

118 阅读1分钟

特定场景

主要解决:不同条件,创建不同实例

应用实例

  • 1.需要一个通用的excel导出功能
  • 2.存在10种不同业务的导出场景
  • 3.使用工厂模式实现
    classDiagram
    ExportStrategy <|.. ExportStrategyBill:implements
    ExportStrategy <|.. ExportStrategyAccount:implements
    ExportService --<| ExportStrategyFactory:使用工厂
    ExportStrategy : +export()void
    ExportStrategyBill : +export()void
    ExportStrategyAccount : +export()void
    ExportStrategyFactory : +getExportStrategy()ExportStrategy
    ExportService : +out()void
   class ExportStrategy {
       <<Interface>>
   }
   class ExportStrategyBill  {
       
   }
@Service
public class ExportService {
    @Autowired
    private ExportStrategyFactory exportStrategyFactory;
    
    /**
     * 导出
     * @return
     */
    public void out(String type) {
        //从工厂取到对应的策略类
        ExportStrategy strategy = exportStrategyFactory.getExportStrategy(type);
        // 执行策略导出方法
        strategy.export();
    }
}