/
DependencyPass.java
92 lines (78 loc) · 1.74 KB
/
DependencyPass.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
package com.peixiao.principle.inversion.improve;
/**
* @Author: Peixiao Zhao
*/
public class DependencyPass {
public static void main(String[] args) {
// 方法 1
// SonyTV sonyTV = new SonyTV();
// OpenAndClose openAndClose = new OpenAndClose();
// openAndClose.open(sonyTV);
// 方法 2
// SonyTV sonyTV = new SonyTV();
// OpenAndClose openAndClose = new OpenAndClose(sonyTV);
// openAndClose.open();
// 方法 3
SonyTV sonyTV = new SonyTV();
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.setTv(sonyTV);
openAndClose.open();
}
}
class SonyTV implements ITV{
@Override
public void play() {
System.out.println("sony大法好");
}
}
// 方式1:通过接口传递实现依赖
// 开关的接口
//interface IOpenAndClode{
// public void open (ITV tv);
//}
//
//interface ITV{
// public void play();
//}
//
//class OpenAndClose implements IOpenAndClode {
// public void open(ITV tv){
// tv.play();
// }
//}
// 方式2: 通过构造方法依赖传递
//interface IOpenAndClose{
// public void open ();
//}
//
//interface ITV{
// public void play();
//}
//
//class OpenAndClose implements IOpenAndClose{
// public ITV tv;
//
// public OpenAndClose(ITV tv){
// this.tv = tv;
// }
// public void open(){
// this.tv.play();
// }
//}
// 方式3: 通过setter方法传递
interface IOpenAndClose{
public void open();
public void setTv(ITV tv);
}
interface ITV {
public void play();
}
class OpenAndClose implements IOpenAndClose{
private ITV tv;
public void setTv(ITV tv){
this.tv = tv;
}
public void open(){
this.tv.play();
}
}