java-如何使用Spring有效地实现策略模式?
作者:互联网
我有一个使用Spring框架在Java 1.5中开发的Web应用程序.应用程序包含“仪表盘”,这些仪表盘是简单的页面,在其中可以重新组合一堆信息,并且用户可以在其中修改某些状态.经理们希望我在数据库中为这三个仪表板添加一个日志记录系统.每个仪表板都有不同的信息,但是应该通过日期和用户登录来跟踪日志.
我想做的是实现这样的Strategy模式:
interface DashboardLog {
void createLog(String login, Date now);
}
// Implementation for one dashboard
class PrintDashboardLog implements DashboardLog {
Integer docId;
String status;
void createLog(String login, Date now){
// Some code
}
}
class DashboardsManager {
DashboardLog logger;
String login;
Date now;
void createLog(){
logger.log(login,now);
}
}
class UpdateDocAction{
DashboardsManager dbManager;
void updateSomeField(){
// Some action
// Now it's time to log
dbManagers.setLogger = new PrintDashboardLog(docId, status);
dbManagers.createLog();
}
}
Appcontext.xml:
<bean id="dashboardManagers" class="...DashboardManagers" />
因此,在此解决方案中,我不使用依赖项注入.以这种方式进行操作是否“正确”(良好实践,性能……)?有没有更好的方法可以使用DI?
注意:我没有写一些基本的东西,例如构造函数和getter / setter.
解决方法:
尽管采用策略模式是完全“正确”的,但考虑到您正在使用Spring的事实-最好使用Spring框架提供的Dependency Injection机制-最好使用您的策略框架必须提供其核心优势之一.
标签:strategy-pattern,dependency-injection,spring,java 来源: https://codeday.me/bug/20191105/1996034.html