首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

设计模式:责任链方式

2014-01-17 
设计模式:责任链模式?2、实例代码package com.leon.chainpublic abstract class Chain {public static int

设计模式:责任链模式

?2、实例代码

package com.leon.chain;public abstract class Chain {public static int One = 1;public static int Two = 2;public static int Three = 3;protected int threshold;protected Chain next;public void setNext(Chain chain) {this.next = chain;}public void message(String msg, int priority) {if (priority <= threshold) {writeMessage(msg);}if (this.next != null) {this.next.message(msg, priority);}}abstract void writeMessage(String msg);}

?

package com.leon.chain;public class Test {public static void main(String[] args) {Chain chain = createChain();chain.message("level 3", Chain.Three);chain.message("level 2", Chain.Two);chain.message("level 1", Chain.One);}public static Chain createChain() {Chain chain1 = new A(Chain.Three);Chain chain2 = new B(Chain.Two);chain1.setNext(chain2);Chain chain3 = new C(Chain.One);chain2.setNext(chain3);return chain1;}}class A extends Chain {public A(int threshold) {this.threshold = threshold;}@Overridevoid writeMessage(String msg) {// TODO Auto-generated method stubSystem.out.println("A:"+msg);}}class B extends Chain {public B(int threshold) {this.threshold = threshold;}@Overridevoid writeMessage(String msg) {// TODO Auto-generated method stubSystem.out.println("B:"+msg);}}class C extends Chain {public C(int threshold) {this.threshold = threshold;}@Overridevoid writeMessage(String msg) {// TODO Auto-generated method stubSystem.out.println("C:"+msg);}}

?在这个例子中,level 1的Message走过了链中所有的单元。

A:level 3
A:level 2
B:level 2
A:level 1
B:level 1
C:level 1

?原文链接:这里

热点排行