单例模式的示例 [英] example for Singleton pattern
问题描述
请给我一个单例模式的实时示例。
访问共享文件的不同线程是单独还是不是?由于每个线程访问文件的同一个实例而不是自己的单个实例。
Please give me a real time example for singleton pattern . Different threads accessing a shared file is singleton or not ? Since each thread access the same instance of the file not individual instances of their own .
推荐答案
是的,但仅当所有线程都访问时同一个文件,你正在使用自定义实现(不是 java.io.File
,也许是一个包装器)
Yes, but only if all threads access the same file, and you are using a custom implementation (not java.io.File
, perhaps a wrapper)
单例模式是一种设计模式,用于将类的实例化限制为一个对象
the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object
单身人士(通常是一个糟糕的选择)是在整个计划中只能有一个实例的类。
Singletons (being often a bad choice) are classes that can have only one instance throughout the whole program.
例如 SingletonConfigFile
可能看起来像这样。请记住:
For example a SingletonConfigFile
might look like this. Have in mind that:
- 它仅用于读取一个文件。这对于配置文件是有意义的。
- 如果您的类可以多次实例化,对于不同的文件,它不是单例。
- 不要使用此代码 - 它没有考虑并发问题,这是一个完全不同的讨论领域。
。
public SingletonConfigFile {
private static String filename = "config.xml";
private File file;
private static SingletonConfigFile instance;
private SingletonConfigFile() {
if (instance != null) {
throw new Error();
}
file = new File(filename);
}
public synchronized SingletonConfigFile getInstance() {
if (instance == null) {
instance = new SignletonConfigFile();
}
return instance
}
public String read() {
// delegate to the underlying java.io.File
}
}
但这个例子处于意义边缘。单身人士用于只有一个物体的情况(如上所述)。例如,它有意义:
But this example is on the edge of sense. Singletons are used in cases when there is only one object (as I stated above). For example it would make sense to have:
-
RingOfPower.getInstance()
- 只有一个力量环(Sauron's),并且不存在更多。 -
Sun.getInstance()
- 仅限一个叫做sun的明星。 - 你的应用程序的所有对象在逻辑上应该只存在一次 - 一个注册表,一个应用程序上下文等。
RingOfPower.getInstance()
- there is only one ring of power (Sauron's), and there can't exist more.Sun.getInstance()
- only one star called "sun".- all objects in the withing of your application that logically should exist only once - a registry, an application context, etc.
这篇关于单例模式的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!