《Android源码设计模式解析和实战》责任链模式

责任链模式是我们发送一个请求,他处理不了就把他给了他的下一级,点击事件和有序广播;

处理者:


public abstract class Loader {
private static final String TAG = "Loader";
protected Loader nextHandle;

public final void handleRequest(int money) {
    if (money <= getLimit()) {
        handle(money);
    } else {
        if (nextHandle != null) {
            nextHandle.handleRequest(money);
        } else {
            Log.i(TAG, "handleRequest: " + "你离职吧");
        }
    }
}

public abstract int getLimit();

public abstract void handle(int money);

}
public class Manager extends Loader {
private static final String TAG = "Manager";

@Override
public int getLimit() {
    return 100;
}

@Override
public void handle(int money) {
    Log.i(TAG, "handle: Manager批复" + money);
}

}

public class CEO extends Loader {
private static final String TAG = "CEO";

@Override
public int getLimit() {
    return 1000;
}

@Override
public void handle(int money) {
    Log.i(TAG, "handle: CEO批复" + money);
}

}
public class BOSS extends Loader {
private static final String TAG = "BOSS";

@Override
public int getLimit() {
    return 10000;
}

@Override
public void handle(int money) {
    Log.i(TAG, "handle: Boss批复" + money);
}

}

使用


public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BOSS boss = new BOSS();
    CEO ceo = new CEO();
    Manager manager = new Manager();
    manager.nextHandle = ceo;
    ceo.nextHandle = boss;
    manager.handleRequest(100);
    manager.handleRequest(1000);
    manager.handleRequest(10000);
    manager.handleRequest(100000);
}

}


log

03-07 18:59:22.584 28406-28406/com.lerz.zenrenliandemo I/Manager: handle: Manager批复100
03-07 18:59:22.584 28406-28406/com.lerz.zenrenliandemo I/CEO: handle: CEO批复1000
03-07 18:59:22.584 28406-28406/com.lerz.zenrenliandemo I/BOSS: handle: Boss批复10000
03-07 18:59:22.584 28406-28406/com.lerz.zenrenliandemo I/Loader: handleRequest: 你离职吧

你可能感兴趣的:(《Android源码设计模式解析和实战》责任链模式)