Summary of common design patterns--responsibility chain model
In the multithreaded programming model, the responsibility chain pattern is a common pattern, the responsibility chain model can decompose a task into small independent task units, so that the whole task at a glance.
Take a crawler to crawl a page for example, assuming that the URL of the scheduling is not a crawler to manage, but there is a special URLDB module to achieve, then a Web page can be decomposed into the following small subtasks. Download the Web page, parse the page, and write the newly discovered link in the current page back to Urldb. After the task is decomposed into small tasks, the output of each small task is the input of the next task, and the entire framework is clear. Log-assisted information that is easy to find where problems occur
Cut the crap, just look at the code.
Processor.java
Public abstract class Processor {
private Processor next;
protected int delta;
public abstract int doprocess (int base);
public void Setnext (Processor next) {
this.next = next;
}
public void process (int base) {
int = doprocess (base);
if (null!= next) {
next.process (result);}}}
Processorchainfactory, responsible for putting small tasks together.
Package zl.study.designpattern.respchain;
public class Processorchainfactory {public
static Processor Assemblechain (Processor ... Processor) {
Processor head = NULL;
Processor pre = null;
if (null = = Processor | | 0 >= processor.length) {return head
;
}
for (int i = 0; i< processor.length i + +) {
processor current = Processor[i];
if (i = = 0) {head
=current;
}
if (null!= pre) {
Pre.setnext (current);
}
Pre = current;
}
return head;
}
Sample Programs
Forget a math problem.
Processoradd.java addition
Package zl.study.designpattern.respchain.test;
Import Zl.study.designpattern.respchain.Processor;
public class Processoradd extends processor{public
processoradd (int delta) {
this.delta = Delta;
}
@Override public
int doprocess (int base) {
Int. result = base + Delta;
SYSTEM.OUT.PRINTLN (result);
return result;
}
Processorsub.java Subtraction
Package zl.study.designpattern.respchain.test;
Import Zl.study.designpattern.respchain.Processor;
public class Processorsub extends processor{public
processorsub (int delta) {
this.delta = Delta;
}
@Override public
int doprocess (int base) {
Int. result = Base-delta;
SYSTEM.OUT.PRINTLN (result);
return result;
}
Main program
Package zl.study.designpattern.respchain.test;
Import zl.study.designpattern.respchain.ProcessorChainFactory;
public class Respchaintest {public
static void Main (String args[]) {
Processoradd add = new Processoradd (1);
Processorsub sub = new Processorsub (2);
Processorchainfactory.assemblechain (add,sub);
Add.process (1);
}
}