What kind of pattern does this static class implement?
package com.mycontainer;
public class MyContainer {
private static ContainerConfig cConfig;
private MyContainer() {开发者_高级运维
}
public static ContainerConfig getConfiguration() {
if (cConfig == null)
cConfig = new ContainerConfig();
return cConfig;
}
}
It's probably the Singleton pattern: http://en.wikipedia.org/wiki/Singleton_pattern#Implementation
I would have to say that it is a poor implementation of the lazy initialization and Singleton pattern. There is no synchronization and hence no thread safety. Under multiple threads accessing this code you may end up with more than one instance.
Update: It is better to have your code like this:
package com.mycontainer;
public class MyContainer {
// static final singleton object to rely on class loader to create it for you
// in a thread safe way
private static final ContainerConfig cConfig = new ContainerConfig();
// private constructor to prevent instantiation
private MyContainer() {}
// getter method for your singleton object
public static ContainerConfig getContainerConfig() {
return cConfig;
}
}
This is definitely Singleton pattern.
- contructor is private, which means that only this class can instantiate itself.
- method getConfiguration() is static and it instantiates private static instance which is returned on request, which ensures that there is only one object of that class at runtime.
Edit: it may be Singleton-FAIL, but it derives from Singleton. ;]
Lazy Initialization. You're delaying initialization until it is needed.
See http://www.javapractices.com/topic/TopicAction.do?Id=34.
精彩评论