public class PaymentAction { private ILogger logger = new FileLogger(); public void pay(BigDecimal payValue) { logger.log("pay begin, payValue is " + payValue); // do otherthing // ... logger.log("pay end"); }
}
初学者的代码,问题存在:
代码无法解耦,每次修改logger的实现类要全局替换
采用工厂模式:
public class PaymentAction { private ILogger logger = LoggerFactory.createLogger(); public void pay(BigDecimal payValue) { logger.log("pay begin, payValue is " + payValue); // do otherthing // ... logger.log("pay end"); } }
public class LoggerFactory { public static ILogger createLogger() { return new ServerLogger(); } }
依然存在问题:
- 工厂类每次都new一个新对象,是不是很浪费,能不能做成单例的,甚至是做成单例和多例是可以配置;
- 不同的功能模块可能需要不同的实现logger
依赖注入:
public class PaymentAction { private ILogger logger; public PaymentAction(ILogger logger) { super(); this.logger = logger; } public void pay(BigDecimal payValue) { logger.log("pay begin, payValue is " + payValue); // do otherthing // ... logger.log("pay end"); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="paymentAction" class="com.springnovel.paymentwithspringxml.PaymentAction"> <constructor-arg ref="serverLogger" /> </bean> <bean id="serverLogger" class="com.springnovel.perfectlogger.ServerLogger" /> </beans>
好处:1.代码完全解耦,外部文件配置
2.灵活多变,给不同功能模块注入所
需要的实现类,实际代码用接口统一
3.单例模式节省消耗,多例模式也容易
配置。
看了Javdroider Hong的文章记录下感悟
网友评论