策略模式替换if else

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.*;

/**
 * @author ftz-lover
 * @version 1.0
 * @date 2023/2/27 21:06
 */
@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;

/**
 * @author ftz-lover
 * @version 1.0
 * @date 2023/2/27 21:07
 */
@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;



/**
 * @author ftz-lover
 * @version 1.0
 * @date 2023/2/28 19:06
 */
@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为空的情况

策略模式是一种行为型设计模式,它可以用来消除繁琐的if-else语句,并实现算法的动态替换策略模式使用面向对象的继承和多态机制,使得同一行为在不同场景下具备不同的实现。 在策略模式中,我们将不同的算法封装成不同的策略类,每个策略类都实现了一个共同的接口或基类。客户端根据需要选择使用哪个策略类,从而实现不同的行为。 使用策略模式可以避免代码中大量的if-else语句,提高代码的可读性和可维护性。同时,策略模式也符合开闭原则,可以方便地添加新的策略类。 以下是一个使用策略模式实现if-else的示例: ```python # 定义策略接口 class Strategy: def do_operation(self): pass # 定义具体的策略类 class StrategyA(Strategy): def do_operation(self): print("执行策略A") class StrategyB(Strategy): def do_operation(self): print("执行策略B") class StrategyC(Strategy): def do_operation(self): print("执行策略C") # 定义上下文类 class Context: def __init__(self, strategy): self.strategy = strategy def execute_strategy(self): self.strategy.do_operation() # 客户端代码 strategy_a = StrategyA() strategy_b = StrategyB() strategy_c = StrategyC() context = Context(strategy_a) context.execute_strategy() # 输出:执行策略A context = Context(strategy_b) context.execute_strategy() # 输出:执行策略B context = Context(strategy_c) context.execute_strategy() # 输出:执行策略C ``` 通过使用策略模式,我们可以将不同的行为封装成不同的策略类,客户端根据需要选择使用哪个策略类,从而实现不同的行为。这样就避免了繁琐的if-else语句,使代码更加清晰和可扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

water-之

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值