这里有一个静态实现,我不明白。我以前使用静态但不广泛,任何人都可以帮助我理解代码。这是代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connection_Class {
String driver_ClassName="com.mysql.jdbc.Driver";
String URL_connection="jdbc:mysql://localhost:3306/vendor";
String user="root";
String password="lifesuckzz";
//can anybody explain what the following line means, especially the static part.......
private static Connection_Class connectionclass=null;
private Connection_Class(){
try{
Class.forName(driver_ClassName);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException{
Connection con=null;
con=DriverManager.getConnection(URL_connection,user,password);
return con;
}
public static Connection_Class getInstance(){
if(connectionclass==null){
//I know its returning an instance here
connectionclass=new Connection_Class();
}
return connectionclass;
}
}
答案 0 :(得分:5)
static
表示变量是类本身的成员(只有一个副本),而不是类的对象成员(每个对象一个)。您可以在没有对象的情况下访问static
变量。在这种情况下,您可以调用Connection_Class.getInstance()
来获取整个程序共享的单个Connection_Class
对象。
答案 1 :(得分:2)
设计模式称为单身设计模式。
当只需要一个对象来协调整个系统的操作时,这很有用
http://en.wikipedia.org/wiki/Singleton_pattern
回答你的问题:
单身人士维护对唯一单例实例的静态引用,并从静态getInstance()方法返回对该实例的引用。
答案 2 :(得分:2)
这是Singleton
设计模式的示例。通过将构造函数标记为私有,您可以确保控制实例化以使每个JVM *具有 一个且仅一个 实例。
public final class Singleton {
private static Singleton INSTANCE = new Singleton();
private Singleton () {
if (INSTANCE != null)
throw new IllegalStateException("Already instantiated.");
}
// getInstance() method here (refer below)
}
关键字static
确保Singleton可以作为类的成员 (如Singleton.getInstance()
)进行访问,而无需构造函数调用现在不可能,因为它已标记为private
。
此外,您的Singleton实现不是线程安全的。 同步您的getInstance()
方法。
public static synchronized Connection_Class getInstance(){
if(connectionclass == null){
connectionclass = new Connection_Class();
}
return connectionclass;
}
这可以避免请求此连接对象的多个线程之间的任何竞争条件。
答案 3 :(得分:1)
这是 singleton 模式的一个示例。它会在您的应用中创建一个连接类的引用(严格来说,在您的类加载器中)。
Singleton在许多OO语言中是一种相当常见的模式,但通常被视为反模式,因为它使测试变得困难。