Design Pattern - Singleton Pattern
This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.
package Main;
public class Test2 {
public int a;
private static Test2 instance = new Test2();
private Test2(){
}
public static Test2 getInstance(){
return instance;
}
}
package Main;
public class Test {
public int a;
private static Test t = null;
private Test(){
}
public static Test instance(){
if(t == null){
t = new Test();
}
return t;
}
}package Main;
public class Main {
public static void main(String[] args) {
Test t1 = Test.instance();
t1.a = 5;
System.out.println(t1.a);
Test t2 = Test.instance();
t2.a = 10;
System.out.println(t1.a);
System.out.println(t2.a);
System.out.println("----------------------------");
Test2 tt2 = Test2.getInstance();
tt2.a = 10;
System.out.println(tt2.a);
Test2 tt3 = Test2.getInstance();
tt3.a = 20;
System.out.println(tt2.a);
System.out.println(tt3.a);
}
}The outcome will be:
5
10
10
----------------------------
10
20
20
package com.company;
public class UserConfig {
private String username;
private String password;
private static UserConfig userConfig = null;
private UserConfig(String username, String password) {
this.username = username;
this.password = password;
}
public static UserConfig getInstance(String username, String password) {
if (userConfig == null) {
userConfig = new UserConfig(username, password);
}
return userConfig;
}
}---------------------------------------------------------------------------------------------
package main;
public class Car {
public int a;
private static Car instance = null;
private Car() {
}
public static Car getInstance() {
if (instance == null) {
synchronized (Car.class) {
if (instance == null)
instance = new Car();
}
}
return instance;
}
}
Комментарии
Отправить комментарий