Skip to content

Instantly share code, notes, and snippets.

@mainlove
Last active Dec 13, 2015
Embed
What would you like to do?
对于下列的情景,
给用户的前置接口
程序逻辑
给用户的后置接口
在不考虑aop实现的前提的下,以下两种做法:
1 定义固定接口,通过某种方法传入到以上代码段
```java
public interface Handler {
void doBefore();
void doAfter();
}
Handler handler=...;
handler.doBefore();
程序逻辑
Handler.doAfter();
```
用户继承Handler即可
2 使用感知的思想,定义两个功能类
'''java
public interface BeforeHandler extends Handler {
void doBefore();
}
public interface AfaterHandler extends Handler{
void doAfter();
}
'''
Handler仅仅是标记类,什么都不做
仍旧存在一个Handler,用于注入代码,
```java
Handler handler = null;
if (handler instanceof BeforeHandler) {
BeforeHandler bh = (BeforeHandler) handler;
bh.doBefore();
}
程序逻辑
if (handler instanceof AfaterHandler) {
AfaterHandler ah = (AfaterHandler) handler;
ah.doAfter();
}
'''
对于用户来讲,可以通过Handler的继承BeforeHandler,AfaterHandler 来实现扩展
```java
public class UserHandler implements AfaterHandler,BeforeHandler{
@Override
public void doBefore() {
}
@Override
public void doAfter() {
}
}
```
#大家觉得那种方式好#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment