So, Using private constructor and factory method, we can create singleton class.
class Mysingleton {
private static Mysingleton instance;
private Mysingleton () {}
public static Mysingleton getInstance() {
if (instance == null) {
instance = new Mysingleton ();
}
return instance;
}
@Override
protected Object clone() {
return this;
}
public static void main(String[] args) {
Mysingleton t1 = Mysingleton.getInstance();
Mysingleton t2 = Mysingleton.getInstance();
System.out.println(t1);
System.out.println(t2);
}
}
//Singleton .java
import java.sql.DriverManager;
import java.sql.SQLException;
public class Singleton {
private static Singleton instance;
private static final String URL = "jdbc:sqlserver://DESKTOP-MITTPRS\\SQLEXPRESS;databaseName=EmpDB;encrypt=true;trustServerCertificate=true;";
private static final String USERNAME = "sa";
private static final String PASSWORD = "swamy";
private Connection connection;
private Singleton() throws SQLException {
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
public static Singleton getInstance() throws SQLException {
if (instance == null || instance.connection.isClosed()) {
instance = new Singleton();
}
return instance;
}
public Connection getConnection() {
return connection;
}
public static void main(String[] args) {
try {
Singleton singleton = Singleton.getInstance();
System.out.println("Connected to SQL Server successfully!");
singleton.getConnection().close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
TooYoungException(String s) {
super(s);
}
}
class TooOldException extends RuntimeException {
TooOldException(String s) {
super(s);
}
}
class CustomUncheckedExceptionDemo {
public static void main(String arg[]) {
int age = Integer.parseInt(arg[0]);
if (age > 60) {
throw new TooOldException("Younger age is already over");
} else if (age < 18) {
throw new TooYoungException("Please wait some more time");
}
System.out.println("Thanks for register");
}
}
=========================================
// A Class that represents use-defined expception
class MyException extends Exception
{
}
// A Class that uses above MyException
public class setText
{
// Driver Program
public static void main(String
args[])
{
try
{
//
Throw an object of user defined exception
throw
new MyException();
}
catch (MyException
ex)
{
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
|
No comments:
Post a Comment