OO设计 - 将工厂深入到分层类结构中

时间:2015-03-02 16:53:52

标签: oop design-patterns

我有一个分层的类结构。假设我正在为一个城市的学生建模:

class District {
    private Map<String, School> schools;

    public School getSchool(String name) {
        School school = schools.get(name);
        if (school == null) {
            school = new School();
            schools.put(name, school);
        return school;
    }
}

class School {
    private Map<String, Classroom> classrooms;

    public Classroom getClassroom(String name) {
        // similar lazy init code
    }
}

class Classroom {
    private Map<String, Pupil> pupils;

    public Pupil getPupil(String name) {
        // similar lazy init code
    }
}

最后

class Pupil {
    private PupilProfile profile = new DefaultPupilProfile();
}

每个对象都是根据需要动态和懒惰地创建的。

现在我想说我想使用不同的PupilProfile实现,这取决于(为了论证)学生的年龄。但是,我不想在Pupil中使用PupilProfile实现的逻辑 - 我想把它分开。我将来可能想要改变它。

我写了一个工厂界面:

interface PupilProfileFactory {

    PupilProfile newPupilProfile(Pupil pupil);

}

和我最初的实施:

class AgeDependentPupilProfileFactory implements PupilProfileFactory {
    @Override
    public PupilProfile newPupilProfile(Pupil pupil) {
        switch (pupil.getAge()) {
            // Case statements returning different implementations
        }
    }
}

此实现在我的应用程序中作为单例存在(例如,在Spring应用程序上下文中)。

我的问题是我现在必须让这家工厂进入学生:

class Pupil {
    private PupilProfile profile = new DefaultPupilProfile();

    public Pupil(PupilProfileFactory factory) {
        this.profile = factory.newPupilProfile(this);
    }
}

实际上,这意味着将PupilProfileFactory传递给对象图的每一层,从顶部(区)到底部(Pupil)通过构造函数或setter。每个中间层都需要为这个工厂设置一个字段,即使它们只是在它们懒惰地创建一个字段时只使用它来将其传递到下面的级别。

这让我感到丑陋(重构的痛苦),我确信必须有更好的方法 - 是吗?

0 个答案:

没有答案