Skip to content

Commit a1d7148

Browse files
committed
x
1 parent 55ee7e3 commit a1d7148

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

somecode/dp/Adapter.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
public class Adapter {
2+
public static void xiaoMing(BicycleInterface b) {
3+
b.ride();
4+
}
5+
6+
public static void main(String[] args) {
7+
Bicycle b = new Bicycle();
8+
Car c = new Car();
9+
10+
xiaoMing(b);
11+
// xiaoMing(c); //类型不匹配
12+
13+
CarAdapter ca = new CarAdapter(c); // 将 Car 适配成 Bicycle
14+
xiaoMing(ca); // 小明可以用了
15+
}
16+
}
17+
18+
class CarAdapter implements BicycleInterface {
19+
private Car car;
20+
21+
public CarAdapter(Car car) {
22+
this.car = car;
23+
}
24+
25+
public void ride() {
26+
car.drive();
27+
}
28+
}
29+
30+
interface BicycleInterface {
31+
void ride();
32+
}
33+
34+
class Bicycle implements BicycleInterface {
35+
public void ride() {
36+
System.out.println("I am riding a bicycle.");
37+
}
38+
}
39+
40+
interface CarInterface {
41+
void drive();
42+
}
43+
44+
class Car implements CarInterface {
45+
public void drive() {
46+
System.out.println("I am driving a car.");
47+
}
48+
}

0 commit comments

Comments
 (0)