class CHandler1 implements Handler {
private Handler handler;
public CHandler1(Handler handler) {
this.handler = handler;
}
public void handRequest(int signal) {
if (signal == 1) {
System.out.println("handle signal 1");
}
else {
handler.handRequest(signal);
}
}
}
class CHandler2 implements Handler {
private Handler handler;
public CHandler2(Handler handler) {
this.handler = handler;
}
public void handRequest(int signal) {
if (signal == 2) {
System.out.println("handle signal 2");
}
else {
handler.handRequest(signal);
}
}
}
class CHandler3 implements Handler {
public void handRequest(int signal) {
if (signal == 3) {
System.out.println("handle signal 3");
}
else {
throw new Error("can't handle signal");
}
}
}
class ChainClient {
public static void main(String[] args) {
Handler h3 = new CHandler3();
Handler h2 = new CHandler2(h3);
Handler h1 = new CHandler1(h2);
h1.handRequest(2);
}
}
//Interpreter
//感觉跟Composite很类似,只不过他分文终结符和非终结符
//Template Method
abstract class TemplateMethod {
abstract void amd1();
abstract void amd2();
//此方法为一个Template Method方法
public void tmd() {
amd1();
amd2();
}
}
//State
//标准型
//状态和操作不应该耦合在一起
class Contexta {
private State st;
public Contexta(int nst) {
changeStfromNum(nst);
}
public void changeStfromNum(int nst) {
if (nst == 1) {
st = new CStatea1();
}
else if (nst == 2) {
st = new CStatea2();
}
throw new Error("bad state");
}
void request() {
st.handle(this);
}
}
interface State {
void handle(Contexta context);
}
class CStatea1 implements State {
public void handle(Contexta context) {
System.out.println("state 1");
//也许在一个状态的处理过程中要改变状态,例如打开之后立即关闭这种效果
//context.changeStfromNum(2);
}
}
class CStatea2 implements State {
public void handle(Contexta context) {
System.out.println("state 2");
}
}
//工厂型
//根据状态不通生成不同的state
//class StateFactory {
//public static State getStateInstance(int num) {
//State st = null;
//
//if (num == 1) {
//st = new CStatea1();
//}
//else if (num == 2) {
//st = new CStatea2();
//}
//
//return st;
//}
//}