我喜欢这个问题,因为它问“有没有更好的方法来做到这一点?
这听起来像你有一种情况,你有一些价值,让我们假设一个整数,将用于几个对象。 “我应该复制这个值,还是应该使用相同的值?”是一个重要的问题。
让我们假设字符串是多个地方使用的东西,并且不会在应用程序的生命周期中发生变化,但您希望灵活地在一个地方更改字符串的内容。例如,如果您正在构建游戏,则允许用户使用的人数可能是整个应用程序中使用的整数。一个好的模式是constant。例如:
public interface ApplicationConstants {
public static Integer PLAYER_LIVES_COUNT = 3;
}
然后需要的常量可以简单地实现常量接口的任何类:
public class Application implements ApplicationConstants {
public static void main(String[] args) {
FirstClass firstClass = new FirstClass(PLAYER_LIVES_COUNT);
FirstClass superObject = new FirstClass(PLAYER_LIVES_COUNT);
}
}
这比硬编码数字3在你的应用程序,因为你有一个地方,一个更好的模式控制这个数字。没有“查找和替换”。
如果FirstClass对象本身是一个将在应用程序中使用的对象,该怎么办?它有多个属性,其他类需要在应用程序中访问。在这种情况下,一个好的模式是singleton pattern。
公共final类FirstClassFactory {
private static FirstClass instance = null;
private FirstClassFactroy() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new FirstClass();
}
return instance;
}
}
然后在你的应用程序,你可以在运行时更改您的Firstclass实例的值,和值将用于正在使用的任何对象更改的Firstclass:
public class Application {
public static void main(String[] args) {
FirstClass firstClass = FirstClassFactory.getInstance();
firstClass.setPlayerLives(3);
}
}
如果您的应用程序的另一个类调用FirstClassFactory.getInstance()
,就会收到alread实例y将playerLives设置为3.
最后,假设您有一个用例,需要向FirstClass对象添加更多数据和功能。一个好的模式可能是扩展或wrapper or decorator pattern。例如:
public class LivesManager {
private FirstClass firstClass;
private String statusMessage = "Number of lives remaining: ";
public LivesManager(FirstClass firstClass) {
this.firstClass = firstClass;
}
public void decrementRemainingLives() {
--firstClass.getLives();
}
public String getLivesMessage() {
return statusMessage + firstClass.getLives();
}
}
最后要注意的:如在评论中提到的,这是很好的做法,使类变量私有和使用getter和setter方法来访问的变量。例如:
public class FirstClass {
private Integer lives;
public FirstClass(Integer lives) {
this.lives = lives;
}
public Integer getLives() {
return lives;
}
public void setLives(Integer lives) {
this.lives = lives;
}
}
希望这会有所帮助,祝你好运!
看到代码不会有什么伤害。 –
曾听说过吸气剂? – Stultuske