这个责任链演示是最基础的责任链使用。
链上有play
、eat
、sleep
服务。通过 restful
进行测试。
restful controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.lou.springboot.controller;
import com.lou.springboot.Message; import com.lou.springboot.ServiceImpl; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController public class DayController {
@Resource private ServiceImpl service;
@GetMapping("/test") public String dayOfThings() { Message message = new Message(true, true, true); return service.dayOfThings(message); } }
|
Message
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package com.lou.springboot;
import lombok.Data;
@Data public class Message { public Boolean eat; public Boolean sleep; public Boolean play;
public Message(Boolean eat, Boolean sleep, Boolean play) { this.eat = eat; this.sleep = sleep; this.play = play; } }
|
责任链演示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| package com.lou.springboot;
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service;
import javax.annotation.Resource; import java.util.List;
interface ComponentConsumer<T> { boolean deal(T t); }
@Component @Order(2) class EatComponent implements ComponentConsumer<Message> {
private static final Logger logger = LoggerFactory.getLogger(Component.class);
@Override public boolean deal(Message message) { return message.getEat(); } }
@Component @Order(3) class SleepComponent implements ComponentConsumer<Message> {
private static final Logger logger = LoggerFactory.getLogger(Component.class);
@Override public boolean deal(Message message) { return message.getSleep(); } }
@Component @Order(1) class PlayComponent implements ComponentConsumer<Message> {
private static final Logger logger = LoggerFactory.getLogger(Component.class);
@Override public boolean deal(Message message) { return message.getPlay(); } }
@Service public class ServiceImpl {
@Resource List<ComponentConsumer> componentConsumerList;
public String dayOfThings(Message message) { StringBuilder stringBuilder = new StringBuilder(); for (ComponentConsumer componentConsumer : componentConsumerList) { if (componentConsumer.deal(message)) { stringBuilder.append("校验通过"); } else { stringBuilder.append("校验不通过");
} } return stringBuilder.toString(); } }
|
通过访问 http://127.0.0.1:8080/test
就好了。