使用接口替代继承

使用组合替代继承,可以复用代码,但不能统一处理。使用接口,针对接口编程,可以实现统一处理不同类型的对象,但接口没有代码实现,无法复用代码。

将组合和接口结合起来,就既可以统一处理,也可以复用代码了。

举个栗子:

先增加一个接口IAdd:

1
2
3
4
public interface IAdd {
void add(int number);
void addAll(int[] numbers);
}

修改Base类代码,让它实现IAdd接口,代码基本不变:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Base implements IAdd {
private static final int MAX_NUM = 1000;
private int[] arr = new int[MAX_NUM];
private int count;

public void add(int number) {
if (count < MAX_NUM) {
arr[count++] = number;
}
}

public void addAll(int[] numbers) {
for (int num : numbers) {
add(num);
}
}
}

修改Child类代码,也是实现IAdd接口,代码基本不变:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Child implements IAdd{
private Base base;
private long sum;

public Child() {
base = new Base();
}

public void add(int number) {
base.add(number);
sum+=number;
}

public void addAll(int[] numbers) {
base.addAll(numbers);
for (int i=0;i<numbers.length;i++) {
sum+=numbers[i];
}
}

public long getSum() {
return sum;
}
}
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2021 Silver Shaded
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信