Java 我应该在我的案例中使用继承还是组合?

Java 我应该在我的案例中使用继承还是组合?,java,inheritance,design-patterns,logging,composition,Java,Inheritance,Design Patterns,Logging,Composition,我正在创建一个与另一个类共享公共代码的类,但不确定应该使用哪种模式。我已经上过的课程: public class TeamA{ private static final Logger LOGGER = Logger.getLogger(TeamA.class); @Autowired private Utility util; public void proceedWithA(){ // do something useful here

我正在创建一个与另一个类共享公共代码的类,但不确定应该使用哪种模式。我已经上过的课程:

public class TeamA{
    private static final Logger LOGGER = Logger.getLogger(TeamA.class);

    @Autowired
    private Utility util; 

    public void proceedWithA(){
        // do something useful here
        updateProgress();
    }

    private void updateProgress(){
        LOGGER.info("Updating progress!");
        // do something to update the progress
    }
}
我正在创建的类TeamB与类TeamA的作用几乎相同,只是在proceedB中,它在调用updateProgress之前做了一些不同的事情

因此,首先我倾向于使用继承,通过创建一个超级类团队来扩展:

public class Team{
    // How should I define the Logger?

    @Autowired
    private Utility util;

    protected void updateProgress(){
        // LOGGER.info("Updating progress!");
        // do something to update the progress
    }
}
我应该如何使用记录器?在TeamA/B类中,它被定义为private static final,但显然在超类中我不能这样做,因为我需要分别为TeamA和TeamB创建一个记录器

我还想到了作文。但似乎我必须将记录器作为参数传递给updateProgress方法。这样行吗,还是有更好的办法

public class TeamA{
    private static final Logger LOGGER = Logger.getLogger(TeamA.class);

    @Autowired
    private Team teamUtil;

    public void proceedWithA(){
        // do something useful here
        teamUtil.updateProgress(LOGGER);
    }
}

public class Team{
    @Autowired
    private Utility util;

    protected void updateProgress(Logger LOGGER){
        LOGGER.info("Updating progress!");
        // do something to update the progress
    }
}
我是设计模式的新手,这件事让我感到困惑。有人能给我一些建议吗?谢谢:

public abstract class Team{
    protected abstract Logger getLogger();

    protected void updateProgress(){
        getLogger().info("Updating progress!");
        // do something to update the progress
    }
}

您的子类现在可以实现getLogger来返回其静态最终记录器。

受保护的void updateProgress位置需要修复,因为它的功能随类而变化。 这里可以做的是创建一个抽象的超类,并将updateProgress抽象为模板模式。让基类为它提供独立的功能。通过这种方式,您可以通过子类/超类变量来使用它。 没有法律规定你必须随时随地使用构图,这要看情况而定。。在您的情况下,您应该使用模板方法模式

public abstract class Team{
    protected abstract Logger getLogger();

    protected void updateProgress(){
        getLogger().info("Updating progress!");
        // do something to update the progress
    }
}