2016年12月17日 星期六

代理、工廠模式 (反射五)

※代理

package inheritate;
    
public interface GrandFather {
    public String say(String data);
}
------------------------------
package inheritate;
    
public class Son implements GrandFather {
    @Override
    public String say(String data) {
        return data;
    }
}


※InvocationHandler

public class MyInvocationHandler implements InvocationHandler {
    private Object obj;
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return method.invoke(obj, args);
    }
    
    public Object proxy(Object obj) {
        this.obj = obj;
        Class<?> objClass = obj.getClass();
        return Proxy.newProxyInstance(objClass.getClassLoader(), objClass.getInterfaces(), this);
    }
}


※測試

MyInvocationHandler mih = new MyInvocationHandler();
GrandFather gf = (GrandFather) mih.proxy(new Son());
System.out.println(gf.say("xxx"));

※利用InvocationHandler即可完成代理的功能



※工廠模式

package inheritate;
    
public interface GrandFather {
    public String say(String data);
}
------------------------------
package inheritate;
    
public class Son implements GrandFather {
    @Override
    public String say(String data) {
        return data + " 1";
    }
}
------------------------------
package inheritate;
    
public class SecondSon implements GrandFather {
    @Override
    public String say(String data) {
        return data + " 2";
    }
}


※工廠類

package inheritate;
    
public class ReflecFactory {
    public static Object getInstance(String className) {
        try {
            return Class.forName(className).newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}



※測試

GrandFather gf1 = (GrandFather) ReflecFactory.getInstance("inheritate.Son");
System.out.println(gf1.say("xxx"));
    
GrandFather gf2 = (GrandFather) ReflecFactory.getInstance("inheritate.SecondSon");
System.out.println(gf2.say("ooo"));

※不管有幾個子類和其他的父子類,工廠類別都不用動

沒有留言:

張貼留言