简体   繁体   English

Java单例设计模式与全局变量

[英]Java singleton design pattern vs global variable

I have developed a "Quiz application in java", which have many features like quiz conduction, instant reporting features, students can post their doubts and all. 我开发了一个“ java测验应用程序”,它具有测验引导,即时报告功能等许多功能,学生可以发表自己的疑问以及所有内容。

I want to maintain the log of the number of students requested for quiz, the number of students that submitted the response, the total active students and some other details. 我想保留要求参加测验的学生人数,提交回复的学生人数,在职学生总数以及其他一些详细信息的日志。

I am using a Global class which has static variables to keep these details. 我正在使用具有静态变量的Global类来保留这些详细信息。 Is it correct way to maintain this or should I want to use the Singleton design pattern ? 是保持这种状态的正确方法还是我应该使用Singleton设计模式?

Kindly give me pros and cons of both and which one to use and when? 请给我两者的优缺点,以及何时使用哪个?

Long story short: by using global variables you're breaking OOP rules (encapsulation). 长话短说:通过使用全局变量,您正在违反OOP规则(封装)。 You will keep using them until your code becomes one big mess. 您将继续使用它们,直到您的代码变得一团糟。 So instead of using global variables I would go for singleton (but make sure it is thread safe). 因此,我不使用全局变量,而是选择单例(但请确保它是线程安全的)。 Neither solutions are great thought. 两种解决方案都不是好主意。

PS There is a lot of information on the internet: PS:互联网上有很多信息:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM