1:举例:我们在博客文章删除的时候需要将对应的文章评论也删除,同样说说等等功能也是一样的道理,说说对应的评论也要删除
2:首先我们写一个接口:DeleteType
3:写三个类实现这个接口,说说,文章,友链
package com.zhi.blog.strategy.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhi.blog.domain.Comment;
import com.zhi.blog.mapper.CommentMapper;
import com.zhi.blog.strategy.DeleteType;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import static com.zhi.common.constant.blog.CommonConst.*;
@Service("articleCommentStrategy")
public class ArticleCommentStrategy implements DeleteType {
@Resource
private CommentMapper commentMapper;
@Override
public void operate(Collection<Long> ids) {
ids.forEach( i ->{
List<Comment> comments = commentMapper.selectList(new LambdaQueryWrapper<Comment>().eq(Comment::getType, ARTICLE_TYPE_VALUE).eq(Comment::getTopicId,i));
commentMapper.deleteBatchIds(comments.stream().map(Comment::getId).collect(Collectors.toList()));
});
}
}
package com.zhi.blog.strategy.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhi.blog.domain.Comment;
import com.zhi.blog.mapper.CommentMapper;
import com.zhi.blog.strategy.DeleteType;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import static com.zhi.common.constant.blog.CommonConst.FRIENDLINK_TYPE_VALUE;
@Service("friendLinkCommentStrategy")
public class FriendLinkCommentStrategy implements DeleteType {
@Resource
private CommentMapper commentMapper;
@Override
public void operate(Collection<Long> ids) {
ids.forEach( i ->{
List<Comment> comments = commentMapper.selectList(new LambdaQueryWrapper<Comment>().eq(Comment::getType, FRIENDLINK_TYPE_VALUE).eq(Comment::getTopicId,i));
commentMapper.deleteBatchIds(comments.stream().map(Comment::getId).collect(Collectors.toList()));
});
}
}
说说同样的道理,里面的大写都是用的全局静态变量
4:写上下文类:DeleteStrategyContext:
package com.zhi.blog.strategy.context;
import com.zhi.blog.strategy.DeleteType;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.Map;
@Service
public class DeleteStrategyContext {
@Resource
private Map<String, DeleteType> deleteTypeMap;
public void operate(String commenttype, Collection<Long> ids){
deleteTypeMap.get(commenttype).operate(ids);
}
}
这里的 Map<String, DeleteType> deleteTypeMap;直接使用@Resource注入,原理就是,当采用了策略模式设计了一个interface,它有多个实现类,应该使用如下的方式进行注入:
@Resource
private Map<String, DeleteType> deleteTypeMap;
解释:@Autowired是按照byType注入的(即按照bean的类型),Map的key就是bean的beanName,value就是实现类,我这里的DeleteType就是上面写的接口,然后对应三个实现类,每一个实现类都有@service注解加自己的类名,以名字的方式注入进去,这样在项目启动的时候,就会实例化这个map,将他作为一个bean注入,
5:业务中使用:
@Resource
private DeleteStrategyContext deleteStrategyContext;
遇到的一些问题:
当类中有自动注入的属性的时候,不要使用new创建对象,要使用自动注入的方式,才不会出现mapper为空的情况