1

有设计问题,也许你可以帮助决定。

我的客户对象可以要求一组对象 class Report。有一组定义的可用报告,根据客户的权限,不同的报告可以包含在返回的集合中。每个请求都会创建报告(每个客户都会在每个请求上获得全新的报告实例)。

我应该使用一种“工厂”来封装报告创建,如下所示:

public class ReportsFactory {

    private UserPermissionsChecker permissionsChecker;

    public Set<Report> createReports() {
        Set<Report> reports = new HashSet<Report>();
        if(permissionsChecker.hasAccessTo('report A')) {
            reports.add(createReportA());
        }
        if(permissionsChecker.hasAccessTo('report B')) {
            reports.add(createReportB());
        }
        if(permissionsChecker.hasAccessTo('report C')) {
            reports.add(createReportC());
        }
        return reports;
    }

    private Report createReportA() {...}
    private Report createReportB() {...}
    private Report createReportC() {...}
}

这是所谓的简单工厂模式的正确用法吗?或者你有其他建议吗?

** 编辑 **

下面的一些评论说这不完全是工厂模式。如果不是,我怎么能这样称呼?

4

2 回答 2

1

I think the design is correct, but this is a wrong usage of the "Factory" word. In the Factory pattern, XxxxFactory creates instances of Xxxx, initializes them if required, but applies no other kind of logic.

This design here seems correct to me, but your class would rather be called ReportsService

And maybe UserPermissionsChecker would be AuthorizationService

Edit: To take into account criticism against the word "Service".

There is currently a quite widespread (I did not say universal) convention in the java world, which consists in having:

  • A purely descriptive business-model implemented by classes emptied of all logic called (maybe mistakenly) POJOs
  • All business logic mainly related to an object Xxx implemented in a procedural style in the methods of a class called XxxService.

I personally don't agree with this coding style and I prefer object oriented programming, but whether we like it or not, this convention exists in the Java EE world and has it's coherence.

Judging bye the coding style of the class submitted by the OP, I inferred that he followed this procedural approach. In that situation, it's better to follow the existing convention and call the class that serves as a container for the procedural code which handles Reports a ReportService.

于 2012-11-09T15:08:58.567 回答
0

对我来说,这看起来有点像构建器模式,从某种意义上说,你有一个对象,你可以构建它的数据。
这与工厂相反,工厂通常返回不同的具体类型的创建对象,
并且通常这些对象的数据构造是在具体类的 CTOR 中完成的,它们的对象是从工厂返回的。

于 2012-11-10T14:18:19.537 回答