把相同的模塊提取出來,做統(tǒng)一處理粱快。一般都是橫向切面秩彤。
如上,數(shù)據(jù)庫增事哭、刪漫雷、改的時(shí)候,都要執(zhí)行一個(gè)保存的過程慷蠕,所以就通過一個(gè)動態(tài)代理珊拼,把保存的操作切出
public class MainActivity extends AppCompatActivity implements DBOperation {
private DBOperation db;
private final static String TAG = "netease >>> ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// db = this;
db = (DBOperation) Proxy.newProxyInstance(DBOperation.class.getClassLoader(),
new Class[]{DBOperation.class}, new DBHander(this));
}
class DBHander implements InvocationHandler {
private DBOperation db;
DBHander(DBOperation db) {
this.db = db;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (db != null) {
Log.e(TAG, "操作數(shù)據(jù)庫之前,開始備份……");
save(); // 查詢數(shù)據(jù)庫后備份流炕,詳細(xì)過程省略
Log.e(TAG, "數(shù)據(jù)備份完成澎现,等待操作");
return method.invoke(db, args);
}
return null;
}
}
// 點(diǎn)擊事件
public void jump(View view) {
// startActivity(new Intent(this, OrderActivity.class));
// 常規(guī)寫法
// db.save();
db.delete();
}
@Override
public void insert() {
Log.e(TAG, "新增數(shù)據(jù)");
}
@Override
public void delete() {
Log.e(TAG, "刪除數(shù)據(jù)");
}
@Override
public void update() {
Log.e(TAG, "修改數(shù)據(jù)");
}
@Override
public void save() {
Log.e(TAG, "保存數(shù)據(jù)");
}
}
上面通過Proxy.newProxyInstance動態(tài)代理,實(shí)現(xiàn)了切面