跳至主要内容

博文

目前显示的是标签为“design-pattern”的博文

Spring 拦截 DAO

缘由 由于要对数据库的部分数据做缓存,并且没有现成的缓存与数据库的一致性的保障机制,所以只能在DAO对数据库操作的同时更新缓存。 为了避免对原有代码的侵入,决定采用spring的aop拦截DAO对数据库的操作然后更新缓存。 分析 尝试 一开始,我实现了如下的代码,对删除进行拦截: @AfterReturning ( pointcut = "execution(public * dao.AccountDao+.deleteX(..))" , returning = "affectedRowCount" ) public void delete (JoinPoint joinPoint, int affectedRowCount) { if (affectedRowCount == 1 ) { xCache.delete((Integer) joinPoint.getArgs()[ 0 ]); } } 但是测试发现,拦截并没有成功。 深入 经检查,spring的配置没有问题,aop的语法也是正确的。那为什么拦截不到呢? 于是怀疑跟AccountDao这个interface有关: public interface AccountDao extends GenericDao { @DAOAction (action = DAOActionType.UPDATE) public int delete (@ DAOParam ("accountId") int accountId); //... } 仔细查看源码,发现这个interface其实并没有实现类!也就是说,这个interface或者他内部的方法是动态生成的。 查看这个bean的定义如下: < bean id = "accountDao" parent = "parentDao" > < property name = "proxyInterfaces" ...

Patterns Learned Fom `Iterator`

Pattern one: When it comes to iterators, we can easily come up with that its use in abstracting the container and simplify the iteration operation like following example shows: Iterator it = container . iterator () while ( it . hasNext ()) { a = it . next (); // do something } No matter which kind of container you are using (the container has to be iterable and as far as I know, the commonly-used container are all iterable.), you can re-use this piece of code without any change. And this may be extract as a method, like following: public void doIterate ( Iterator it ) { while ( it . hasNext ()) { a = it . next (); // do something } } You can even make it more general with another parameter: public void doIterate ( Iterator it , Function f ) { while ( it . hasNext ()) { a = it . next (); f ( a ); } } This kind of design pattern can isolate the module of handling elements in container, whic...

Singleton and Synchronization

Why synchronized in singleton I will describe what I encounter to convince you it is really needed to do so. I have the Class A in the Thread-use : Singleton s1 = Singleton.getInstance(); synchronized(s1){ while (!B.ready){ s1.wait(); } // read from singleton } Then Class B in Thread-readData : // notice the volatile static volatile boolean ready = false; Singleton s2 = Singleton.getInstance(); synchronized(s2){ // read data than write to singleton ready = true; s2.notify(); } Then Singleton : public static Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } This getInstance() is not synchronized now. If the first thread enter the if clause first, then the second thread get the cpu also enter it ( if clause ) when the instance are still null , so they create two Singleton and return separately . As a result, the s1 and s2 point to the different objects which cause...