责任链模式(Chain of Responsibility Pattern):多个对象组成一条职责链,然后按照它们在职责链上的顺序处理请求。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。 在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。
import Support from "./Support"; import Trouble from "./Trouble"; /** * 解决奇数问题 */ export default class OddSupport extends Support { constructor(name: string) { super(name); }
import NoSupport from "./NoSupport"; import Support from "./Support"; import LimitSupport from "./LimitSupport"; import SpecialSupport from "./SpecialSupport"; import OddSupport from "./OddSupport"; import Trouble from "./Trouble";
const alice: Support = new NoSupport("Alice"); const bob: Support = new LimitSupport("Bob", 100); const charlie: Support = new SpecialSupport("Charlie", 429); const diana: Support = new LimitSupport("Diana", 200); const elmo: Support = new OddSupport("Elmo"); const fred: Support = new LimitSupport("Fred", 300);
alice.setNext(bob).setNext(charlie).setNext(diana).setNext(elmo).setNext(fred); for (let i = 0; i < 500; i += 33) { alice.support(new Trouble(i)); }
result
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
[Trouble 0] is resolved by [Bob] [Trouble 33] is resolved by [Bob] [Trouble 66] is resolved by [Bob] [Trouble 99] is resolved by [Bob] [Trouble 132] is resolved by [Diana] [Trouble 165] is resolved by [Diana] [Trouble 198] is resolved by [Diana] [Trouble 231] is resolved by [Elmo] [Trouble 264] is resolved by [Fred] [Trouble 297] is resolved by [Elmo] [Trouble 330] canot be resolved [Trouble 363] is resolved by [Elmo] [Trouble 396] canot be resolved [Trouble 429] is resolved by [Charlie] [Trouble 462] canot be resolved [Trouble 495] is resolved by [Elmo]