You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
2.8 KiB

/**
* Simulates an expensive object: database connection (time-consuming creation, high resource usage)
* Implements Prototype interface to support cloning
* @author chuyang
* @version 1.0
*/
public class DatabaseConnection implements Prototype<DatabaseConnection> {
/**
* Connection unique identifier
*/
private String connectionId;
/**
* Database URL
*/
private String databaseUrl;
/**
* Whether the connection is currently in use (pool management status)
*/
private boolean isInUse;
public ConnectionPoolManager m_ConnectionPoolManager;
public DatabaseConnection(){
this.connectionId = "";
this.databaseUrl = "";
this.isInUse = false;
}
@Override
public void finalize() throws Throwable {
// Cleanup when connection is closed
System.out.println("Connection " + connectionId + " is being finalized");
}
/**
* Constructor: Simulates high-cost creation scenarios (network connections, authentication, etc.)
*
* @param connectionId Connection ID
* @param databaseUrl Database URL
*/
public DatabaseConnection(String connectionId, String databaseUrl){
// Simulate time-consuming connection creation
try {
Thread.sleep(100); // Simulate connection creation delay
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
this.connectionId = connectionId;
this.databaseUrl = databaseUrl;
this.isInUse = false;
System.out.println("Connection " + connectionId + " created to " + databaseUrl);
}
/**
* Reset connection state: Called when returning to pool, clears temporary data and marks as idle
*/
public void reset(){
// Clear temporary data
this.isInUse = false;
System.out.println("Connection " + connectionId + " has been reset");
}
/**
* Clone method: Used to quickly copy objects (more efficient than new)
* @return Cloned object
*/
@Override
public DatabaseConnection clone(){
try {
// Create new connection object and copy properties
DatabaseConnection cloned = (DatabaseConnection) super.clone();
cloned.connectionId = this.connectionId + "_clone";
cloned.databaseUrl = this.databaseUrl;
cloned.isInUse = false;
System.out.println("Connection " + connectionId + " cloned as " + cloned.connectionId);
return cloned;
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Clone failed", e);
}
}
// Getter and Setter methods
public String getConnectionId() {
return connectionId;
}
public void setConnectionId(String connectionId) {
this.connectionId = connectionId;
}
public String getDatabaseUrl() {
return databaseUrl;
}
public void setDatabaseUrl(String databaseUrl) {
this.databaseUrl = databaseUrl;
}
public boolean isInUse() {
return isInUse;
}
public void setInUse(boolean inUse) {
isInUse = inUse;
}
}