如何有效地实施弹簧战略模式? [英] How to efficiently implement a strategy pattern with spring?
问题描述
我有一个使用Spring框架在Java 1.5中开发的Web应用程序。应用程序包含仪表板,这些页面是简单的页面,其中一组信息被重新分组,用户可以在其中修改某些状态。管理人员希望我在数据库中为三个仪表板添加日志记录系统。每个仪表板都有不同的信息,但日志应该按日期和用户登录进行跟踪。
I have a web application developped in Java 1.5 with Spring framework. Application contains "dashboards" which are simple pages where a bunch of information are regrouped and where user can modify some status. Managers want me to add a logging system in database for three of theses dashboards. Each dashboard has different information but the log should be traced by date and user's login.
我想要做的是实现类似这样的策略模式:
What I'd like to do is to implement the Strategy pattern kind of like this :
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:
Appcontext.xml :
<bean id="dashboardManagers" class="...DashboardManagers" />
在这个解决方案中,我没有使用依赖注入。以这种方式做到这一点是正确的(良好做法,表现......)有没有更好的方法可以使用DI?
In this solution I'm therefore not using dependency injection. Is it "correct" (good practice, performance, ...) to do it this way ? Is there a better way where I could use DI ?
注意:我没有写基本的东西,比如构造函数和getter / setter。
推荐答案
尽管采用策略模式完全正确,但考虑到你使用Spring的事实 - 使用Spring提供的依赖注入机制将更好框架 - 也可以将您的框架提供的内容作为其核心优势之一。
While it is perfectly "correct" to employ the strategy pattern as you have, but considering the fact that you're using Spring - it would be better to employ the Dependency Injection mechanism provided by the Spring framework - might as well put to use what your framework has to offer as one of its core strengths.
这篇关于如何有效地实施弹簧战略模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!