Fork me on GitHub
posts - 148,  comments - 5,  views - 84855

   定义一个接口

1
2
3
4
5
6
package com.baidu.test;
 
public interface Person {
    public abstract void eat();
    public abstract void sleep();
}

    定义一个类实现该接口

1
2
3
4
5
6
7
8
9
10
11
12
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类(在吃饭前需要洗手)

1
2
3
4
5
6
7
8
9
10
package com.baidu.test;
 
public class StudentStrengthenExtends  extends Student{
    //我们需要在吃饭前进行洗手
    @Override
    public void eat() {
        System.out.println("洗完手了");
        super.eat();
    }
}

    测试:

1
2
3
4
5
6
public class Test {
    public static void main(String[] args) {
        Person p=new StudentStrengthenExtends();
        p.eat();
    }
}

    输出结果:

1
2
洗完手了
吃饭中....

  

  2.装饰者设计模式

      前提:

        a.增强类和被增强类不许实现相同的接口;

        b.在增强类中获得被增强类的引用;

      缺点:

        接口中的方法过多,重写很多其他方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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();
         
    }
}

  测试类

1
2
3
4
5
6
public class Test {
    public static void main(String[] args) {
        Person p=new StudentStrengthenDecorate(new Student());
        p.eat();
    }
}

  输出结果:

1
2
Decorate洗完手了
吃饭中....

  3.动态代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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;
    }
     
     
}

  测试:

1
2
3
4
5
6
7
8
9
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();
    }
}

  

posted on   TopTime  阅读(258)  评论(0编辑  收藏  举报
< 2025年1月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示