增強 修改對象的集中方法(繼承、裝飾者模式、動態代理)

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.junit.Test;

interface 狗{
	public void run();
}

public class Dog implements 狗 {
	public void run(){
		System.out.println("run!!!!!!");
	}
	
	//動態代理增強方法
	public static void main(String[] args) {
		//繼承
		SuperDog sd=new SuperDog();
		sd.run();
		
		//裝飾模式
//		Dog dog = new Dog();
//		BigDog bd=new BigDog(dog);
//		bd.run();
		
		
		//動態代理
//		final Dog dog = new Dog();
//		狗 proxyDog = (狗)Proxy.newProxyInstance(dog.getClass().getClassLoader(), dog.getClass().getInterfaces(), 
//			new InvocationHandler(){
//			public Object invoke(Object proxy, Method method, Object[] args)
//					throws Throwable {
//				if("run".equals(method.getName())){
//					System.out.println("Proxy Dog");
//				}
//				return method.invoke(dog, args);
//			}
//		});
//		
//		proxyDog.run();
	}
}

//繼承方式增前父類的方法
class SuperDog extends Dog{
	@Override
	public void run() {
		System.out.println("SuperDog ");
		super.run();
	}
}

//裝飾模式增強被裝飾者的方法
class BigDog implements 狗{
	private Dog dog;
	public BigDog(Dog dog){
		this.dog = dog;
	}
	public void run() {
		System.out.println("BigDog ");
		dog.run();
	}
	
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章