是否可以继承基数为class的单例class(非单例class)。如果是,这是一个好习惯吗?
Is it possible to inherit a singleton class with a base class (non-singleton class). If yes, is it a good practice?
我实际上正在尝试实现一些东西,其中单例 class 将扩展非单例 class。
我试过阅读多个答案,但其中 none 回答了我的问题。
class Parent{
// Code goes here
}
class MySingleton extends Parent{
// Code goes here
}
我现在有 2 个问题。
1) 这在 java/kotlin 中可行吗?
2) 如果是,这是一种好的做法吗?请提供一些参考。
1) Is this possible in java?
是的,但是。
这取决于您如何实现单例。多年来,单例已成为一种反模式,当您仍然使用它时,最好使用 enums:
public enum SomeSingleton {
INSTANCE;
...
这当然:当你想扩展父级时不起作用 class。
2) If yes, is it a good practice? Please provide some reference.
如前所述,如今(大部分)单例被认为是不好的做法。所以添加 另一个 约束肯定不会让事情变得更好。
从概念上讲,这听起来不对。如果有人这样做怎么办:
List<Parent> someInstances = Arrays.asList(parentInstanceA, parentInstanceB, thatSingletonInstanceOfMySingleton);
突然间,你有很多东西当然不完全相同,但好吧,它们都很好地进入了那个列表。
长话短说:我不会这样做。如果有的话,使用 enum,然后考虑使用组合而不是继承。
我实际上正在尝试实现一些东西,其中单例 class 将扩展非单例 class。
我试过阅读多个答案,但其中 none 回答了我的问题。
class Parent{
// Code goes here
}
class MySingleton extends Parent{
// Code goes here
}
我现在有 2 个问题。
1) 这在 java/kotlin 中可行吗?
2) 如果是,这是一种好的做法吗?请提供一些参考。
1) Is this possible in java?
是的,但是。
这取决于您如何实现单例。多年来,单例已成为一种反模式,当您仍然使用它时,最好使用 enums:
public enum SomeSingleton {
INSTANCE;
...
这当然:当你想扩展父级时不起作用 class。
2) If yes, is it a good practice? Please provide some reference.
如前所述,如今(大部分)单例被认为是不好的做法。所以添加 另一个 约束肯定不会让事情变得更好。
从概念上讲,这听起来不对。如果有人这样做怎么办:
List<Parent> someInstances = Arrays.asList(parentInstanceA, parentInstanceB, thatSingletonInstanceOfMySingleton);
突然间,你有很多东西当然不完全相同,但好吧,它们都很好地进入了那个列表。
长话短说:我不会这样做。如果有的话,使用 enum,然后考虑使用组合而不是继承。