1. 单例模式
保证被创建一次,节省系统的开销。
// 省略 get set
public final class GlobalDataMgr {
private static final GlobalDataMgr MGR = new GlobalDataMgr();
private String userName;
private String passWord;
public static GlobalDataMgr getInstance(){
return MGR;
}
}
2. 代理模式
就是相当于第三方,中介,比如在结婚中,我们关注的事只是结婚这一件事,但是结婚还有宴请宾客、组织会场、司仪主持等其他繁琐的事,这些事就可以交给婚介所处理,然后结婚的这个节点实际上婚介所是用我们的真实身份,也就是我们自己去完成的。所以这里的婚介所就相当于代理。(简而言之,使用代理就是为了帮我们做一些额外的事,我们只需要关注自己的事即可)
注:代理 代理的是接口。
静态代理
// 原始接口(真实角色,即我们)
public interface DemoInterface {
void add();
void del();
void edit();
void query();
default void defaultMethod() {
System.out.println("这是一个默认方法,实现接口时可重写,也可不重写");
}
}
// 真实角色的实现
public class DemoInterfaceImpl implements DemoInterface {
@Override
public void add() {
System.out.println("增加。。");
}
@Override
public void del() {
System.out.println("删除。。");
}
@Override
public void edit() {
System.out.println("更新。。");
}
@Override
public void query() {
System.out.println("查询。。");
}
}
// 代理角色,在这里的作用相当于是加了一些 日志或者说是方法执行前的说明
public class DemoInterfaceProxy implements DemoInterface {
private DemoInterfaceImpl demoInterface;
public void setDemoInterface(DemoInterfaceImpl demoInterface) {
if (null == demoInterface){
demoInterface = new DemoInterfaceImpl();
}
this.demoInterface = demoInterface;
}
@Override
public void add() {
log();
demoInterface.add();
}
@Override
public void del() {
demoInterface.del();
}
@Override
public void edit() {
demoInterface.edit();
}
@Override
public void query() {
log();
demoInterface.query();
}
private void log(){
System.out.println("增加日志功能");
}
}
//主类
public class Main {
public static void main(String[] args) {
DemoInterfaceImpl demoInterface = new DemoInterfaceImpl();
DemoInterfaceProxy proxy = new DemoInterfaceProxy();
proxy.setDemoInterface(demoInterface);
proxy.add();
}
}
动态代理
public class ProxyInvocationHandle implements InvocationHandler {
//被代理的接口
private DemoInterface demoInterface;
public void setDemoInterface(DemoInterface demoInterface) {
this.demoInterface = demoInterface;
}
// 生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),demoInterface.getClass().getInterfaces(),this);
}
/**
* 处理代理实例,并返回成功
* @param proxy
* @param method
* @param args
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 动态代理的本质,使用反射机制实现
before();
Object invoke = method.invoke(demoInterface, args);
after();
return invoke;
}
private void before(){
System.out.println("执行前。。");
}
private void after(){
System.out.println("执行后。。");
}
public static void main(String[] args) {
// 真实角色
DemoInterface demoInterface = new DemoInterfaceImpl();
// 代理角色:无
ProxyInvocationHandle proxy = new ProxyInvocationHandle();
// 把真实角色赋给代理
proxy.setDemoInterface(demoInterface);
// 获得代理角色
DemoInterface demoInterfaceProxy = (DemoInterface)proxy.getProxy();
// 通过代理角色调用方法
demoInterfaceProxy.query();
}
}