学习&延伸 用 Collections.unmodifiableList
磊磊

用 final 修饰的变量,对象属性可以修改的

我在想有什么方法可以限制修改吗?

于是搜索后了解到有一个 Collections 里有一个内部类 UnmodifiableCollection ;

  • UnmodifiableCollection 这个类重写了 Collection 的添加和修改方法,使其调用这个方法会抛 UnsupportedOperationException(不支持的操作异常)

  • 可以用 Collections.unmodifiableList(yourList) 来让你的类不能用添加修改方法

总结

  • 当我们不想这个类调用某些方法时,可以重写这个类的方法。

实现

  • 自己照抄思路实现了一下,哈哈,其是就是多态的体现。
  • 为什么不用继承做呢?我觉得效果是一样的.但是是继承只能继承一个,接口能实现多个。
1
2
3
4
5
6
7
8
public interface FeatureHaveMouth {

/**
* 吃粑粑
*/
void eatShit();

}
1
2
3
4
5
6
7
8
public class Dog implements FeatureHaveMouth {

@Override
public void eatShit() {
System.out.println("Dog 吃粑粑,Dog 喜欢吃粑粑");
}

}
1
2
3
4
5
6
7
8
9
10
11
12
public class TrainDog implements FeatureHaveMouth {

@Override
public void eatShit() {
System.out.println("Dog 吃粑粑,Dog 喜欢吃粑粑,但是我是 TrainDog 就算我喜欢吃我也不吃");
}

public static FeatureHaveMouth train(FeatureHaveMouth featureHaveMouth) {
System.out.println("====Training====");
return new TrainDog();
}
}
  • Test
1
2
3
4
5
6
7
8
9
10
11
public class TestFeatHaveMouth {

@Test
public void testDog() {
FeatureHaveMouth dog = new Dog();
dog.eatShit();
FeatureHaveMouth trainDog = TrainDog.train(dog);
trainDog.eatShit();
}

}
  • 测试结果

image

由 Hexo 驱动 & 主题 Keep
访客数 访问量