定义一个接口
package com.baidu.test; public interface Person { public abstract void eat(); public abstract void sleep(); }
定义一个类实现该接口
package com.baidu.test; public class Student implements Person{ @Override public void eat() { System.out.println("吃饭中...."); } @Override public void sleep() { System.out.println("睡觉中...."); } }
增强类的实现(三种方式)
1.继承
必须要能控制这个(增强类)类的构造方法;
需要增强Student类(在吃饭前需要洗手)
package com.baidu.test; public class StudentStrengthenExtends extends Student{ //我们需要在吃饭前进行洗手 @Override public void eat() { System.out.println("洗完手了"); super.eat(); } }
测试:
public class Test { public static void main(String[] args) { Person p=new StudentStrengthenExtends(); p.eat(); } }
输出结果:
洗完手了 吃饭中....
2.装饰者设计模式
前提:
a.增强类和被增强类不许实现相同的接口;
b.在增强类中获得被增强类的引用;
缺点:
接口中的方法过多,重写很多其他方法。
package com.baidu.test; public class StudentStrengthenDecorate implements Person{ private Student s; public StudentStrengthenDecorate(Student s) { this.s=s; } @Override public void sleep() { // TODO Auto-generated method stub } @Override public void eat() { System.out.println("Decorate洗完手了"); s.eat(); } }
测试类
public class Test { public static void main(String[] args) { Person p=new StudentStrengthenDecorate(new Student()); p.eat(); } }
输出结果:
Decorate洗完手了 吃饭中....
3.动态代理
package com.baidu.test; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class StudentStrengthenProxy implements InvocationHandler{ private Person p; public StudentStrengthenProxy(Person p) { this.p=p; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if("eat".equalsIgnoreCase(method.getName())){ System.out.println("洗手了"); method.invoke(p, args); } return null; } }
测试:
import java.lang.reflect.Proxy; public class Test { public static void main(String[] args) { Person p=new Student(); Person p1 = (Person) Proxy.newProxyInstance(p.getClass().getClassLoader(), p.getClass().getInterfaces(), new StudentStrengthenProxy(p)); p1.eat(); } }