gpt4 book ai didi

java - 标记接口(interface),实现与导入

转载 作者:行者123 更新时间:2023-11-30 07:24:37 24 4
gpt4 key购买 nike

如果我有一个简单的标记接口(interface)(不包含任何方法),其中包含在我的整个应用程序中使用的常量,那么导入该接口(interface)的类与实际实现该接口(interface)之间有什么区别吗?

接口(interface):

public interface MyConstants {
String constant1 = "constant1";
String constant2 = "constant2";
}

实现:

public class MyClass implements MyConstants {
public MyClass(){
System.out.println(constant1);
}
}

导入:

import common.constants.MyConstants
public class MyClass {
public MyClass(){
System.out.println(MyConstants.constant1);
}
}

最佳答案

实现它会是一个反模式:

In the Java programming language, the constant interface pattern describes the use of an interface solely to define constants, and having classes implement that interface in order to achieve convenient syntactic access to those constants. However, since constants are very often merely an implementation detail, and the interfaces implemented by a class are part of its exported API, this practice amounts to putting implementations details into the API, which is considered inappropriate. [1][2] In general, collecting system constants into classes independent of behaviour, might create a poor object-oriented design, because it is often a sign of low cohesion. It is for these reasons that implementing constants interfaces is considered to be an anti-pattern.

http://en.wikipedia.org/wiki/Constant_interface

关于标记接口(interface),你可以查看它here .

关于java - 标记接口(interface),实现与导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11434655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com