动态代理和装饰者模式代码案例

public interface Person{
	void say(String say);
	void learn(String learn);
}
// 需要增强的对象
class Student implements Person{

	@Override
	public void say(String say) {
		System.out.println(say);
	}

	@Override
	public void learn(String learn) {
		System.out.println(learn);
		
	}
	
}
// 增强的对象
class MyIsStudent implements Person{
	private Student student;
	
	public MyIsStudent(Student student) {
		this.student=student;
	}

	@Override
	public void say(String say) {
		System.out.println("开始增强------学生说话");
		student.say(say);
		System.out.println("结束增强------学生说话");
	}

	@Override
	public void learn(String learn) {
		System.out.println("开始增强------学生学习");
		student.learn(learn);
		System.out.println("结束增强------学生学习");
		
	}
	
	
}
public static void main(String[] args) throws ParseException {
       // 动态代理增强
		Person person = (Person) Proxy.newProxyInstance(Student.class.getClassLoader(), Student.class.getInterfaces(), new InvocationHandler() {
			// 常量对象
			private Student student=new Student();
			
			
			/* 
			 * proxy:代理对象
			 * method:调用的方法
			 * args:方法重的参数
			 * 
			 */
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//				
				Object invoke =null;
				if("say".equals(method.getName())) {
					for (int i = 0; i < args.length; i++) {
						System.out.println("增强方法的参数---"+(String)args[i]);
					}
					System.out.println("开始增强say--------");
					invoke = method.invoke(student, args);
					System.out.println("结束增强say--------");
				}
				if("learn".equals(method.getName())) {
					for (int i = 0; i < args.length; i++) {
						System.out.println("增强方法的参数---"+(String)args[i]);
					}
					System.out.println("开始增强learn--------");
					invoke = method.invoke(student, args);
					System.out.println("结束增强learn--------");
				}
				
				return invoke;
			}
		});
		
		person.say("学生说话");
		person.learn("学生学习");
		
		// 装饰着模式增强
		MyIsStudent myIsStudent = new MyIsStudent(new Student());
		myIsStudent.say("学生说话");
		myIsStudent.learn("学生学习");
		
	}
	动态代理通过反射对方法进行增强,装饰模式是通过传递对想进行方法增强对代码无侵入,扩展性好。静态代理也就是装饰模式

你可能感兴趣的:(Java,动态代理和装饰模式)