- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProxyTest.java
More file actions
Latest commit
93 lines (67 loc) · 1.8 KB
/
Copy pathProxyTest.java
File metadata and controls
93 lines (67 loc) · 1.8 KB
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
packageJavaPatternDemos;
/**
* 代理 和 装饰器
* 代理: 一般只是该对象,同时可能会新增功能
* 装饰器:一般是接口实现,只是对接口的方法进行拓展
*
*/
publicclassProxyTest {
publicstaticvoidmain(String[] args) {
AppleProductapple_1 = newAppleProduct();
AppleProxyoneProxy = newAppleProxy(apple_1);
oneProxy.eat();
oneProxy.cook();
AppleProductapple_2 = newAppleProduct();
MyProductoneDecorator = newProductDecoratorClean(newProductDecoratorLogger(apple_2));
oneDecorator.eat();
}
}
interfaceMyProduct {
voideat();
}
classAppleProductimplementsMyProduct {
@Override
publicvoideat() {
System.out.println("eat apple");
}
}
classAppleProxyimplementsMyProduct {
privateAppleProductprod;
publicAppleProxy(AppleProductmApple){
prod = mApple;
}
@Override
publicvoideat() {
System.out.println("this is a poxy");
prod.eat();
}
// 还可以有新的功能
publicvoidcook(){
System.out.println("cooking apple");
}
}
// -----------------------------------
// 下面是装饰器
// -----------------------------------
classProductDecoratorLoggerimplementsMyProduct {
privateMyProductaProd;
publicProductDecoratorLogger(MyProductmProduct){
aProd = mProduct;
}
@Override
publicvoideat() {
System.out.println("log: eating apple");
aProd.eat();
}
}
classProductDecoratorCleanimplementsMyProduct {
privateMyProductaProd;
publicProductDecoratorClean(MyProductmProduct){
aProd = mProduct;
}
@Override
publicvoideat() {
System.out.println("clean before eating");
aProd.eat();
}
}