-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProxyTest.java
93 lines (67 loc) · 1.8 KB
/
ProxyTest.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package JavaPatternDemos;
/**
* 代理 和 装饰器
* 代理: 一般只是该对象,同时可能会新增功能
* 装饰器:一般是接口实现,只是对接口的方法进行拓展
*
*/
public class ProxyTest {
public static void main(String[] args) {
AppleProduct apple_1 = new AppleProduct();
AppleProxy oneProxy = new AppleProxy(apple_1);
oneProxy.eat();
oneProxy.cook();
AppleProduct apple_2 = new AppleProduct();
MyProduct oneDecorator = new ProductDecoratorClean(new ProductDecoratorLogger(apple_2));
oneDecorator.eat();
}
}
interface MyProduct {
void eat();
}
class AppleProduct implements MyProduct {
@Override
public void eat() {
System.out.println("eat apple");
}
}
class AppleProxy implements MyProduct {
private AppleProduct prod;
public AppleProxy(AppleProduct mApple){
prod = mApple;
}
@Override
public void eat() {
System.out.println("this is a poxy");
prod.eat();
}
// 还可以有新的功能
public void cook(){
System.out.println("cooking apple");
}
}
// -----------------------------------
// 下面是装饰器
// -----------------------------------
class ProductDecoratorLogger implements MyProduct {
private MyProduct aProd;
public ProductDecoratorLogger(MyProduct mProduct){
aProd = mProduct;
}
@Override
public void eat() {
System.out.println("log: eating apple");
aProd.eat();
}
}
class ProductDecoratorClean implements MyProduct {
private MyProduct aProd;
public ProductDecoratorClean(MyProduct mProduct){
aProd = mProduct;
}
@Override
public void eat() {
System.out.println("clean before eating");
aProd.eat();
}
}