代理模式
如果加入容器的目标对象有实现接口,用JDK代理
如果目标对象没有实现接口,用Cglib代理
静态代理
JDK代理
Cglib代理
public class MyTest {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer(); //主要的增强类
enhancer.setSuperclass(MyTest.class); //设置父类,被增强的类
enhancer.setCallback(new MethodInterceptorImpl()); //回调对象
MyTest o = (MyTest) enhancer.create();//用cglibProxy来增强UserServiceImpl
String ok = o.test();
System.out.println(ok);
}
public String test() {
System.out.println("test");
return "ok";
}
private static class MethodInterceptorImpl implements MethodInterceptor {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("++++++before " + methodProxy.getSuperName() + "++++++");
System.out.println(method.getName());
Object o1 = methodProxy.invokeSuper(o, objects);
System.out.println("++++++before " + methodProxy.getSuperName() + "++++++");
return o1;
}
}
}
参考文档
https://www.cnblogs.com/cenyu/p/6289209.html
观察者设计模式
定义一个被观察者A
public interface ObserverB extends Observer {
}
定义一个被观察者B
public interface ObserverB extends Observer {
}
定义观察者
public class MyObservable extends Observable {
public void test(){
setChanged();
notifyObservers("test");
}
}
调用
public static void main(String[] args) {
MyObservable observable = new MyObservable();
ObserverA observerA = (o, arg) -> {
//等待通知
System.out.println("As我已经被通知了");
};
ObserverB observerB = (o, arg) -> {
//等待通知
System.out.println("Bs我已经被通知了");
};
observable.addObserver(observerA);
observable.addObserver(observerB);
observable.test();
}
扩展:
spring的事件发布
订阅发布