首页 > 代码库 > 单例模式之饿汉式
单例模式之饿汉式
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; //接口 interface MyInterface { public void action(); } // 被代理类 class MyObject implements MyInterface { @Override public void action() { System.out.println("我是被代理类,执行action!"); } } //被代理接口 interface ClothFactory{ public void productCloth(); } //被代理类 class NikeClothFactory implements ClothFactory{ @Override public void productCloth() { System.out.println("我是被代理类,Nike 生产衣服"); } } //实现InvocationHandler接口的子类 class MyInvocationhandler implements InvocationHandler { private Object obj; public void setObject(Object obj) { this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("动态代理类执行,收代理费"); Object returnVal = method.invoke(obj, args); return returnVal; } } //动态代理类 class MyProxy { public static Object getProxyInstance(Object obj, InvocationHandler handler) { return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj .getClass().getInterfaces(), handler); } } public class TestProxy { /** * @Title: main * @Description: * @param: * @return void * @user: wangzg * @Date:2014-10-27 * @throws */ public static void main(String[] args) { // TODO Auto-generated method stub //被代理类 MyObject myObject = new MyObject(); MyInvocationhandler myInvocationhandler = new MyInvocationhandler(); myInvocationhandler.setObject(myObject); Object myProxy = MyProxy.getProxyInstance(myObject, myInvocationhandler); MyInterface myInterface = (MyInterface)myProxy; myInterface.action(); NikeClothFactory nikeClothFactory = new NikeClothFactory(); myInvocationhandler.setObject(nikeClothFactory); Object myProxyNike = MyProxy.getProxyInstance(nikeClothFactory, myInvocationhandler); ClothFactory clothFactory = (ClothFactory)myProxyNike; clothFactory.productCloth(); } }
单例模式之饿汉式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。