Singleton Pattern
Always return the same instance, prevent the user to initialise their own instance.
package designpatterns.singleton;
public class UserSetting {
private String theme;
private Integer fontSize;
private static UserSetting instance;
private UserSetting () {
// Disable initalising
}
public static UserSetting getInstance() {
if (instance == null) {
instance = new UserSetting();
}
return instance;
}
public void setFontSize(Integer fontSize) {
this.fontSize = fontSize;
}
public String getTheme() {
return theme;
}
public Integer getFontSize() {
return fontSize;
}
public void setTheme(String theme) {
this.theme = theme;
}
}
package designpatterns.singleton.test;
import designpatterns.singleton.UserSetting;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class UserSettingTest {
@Test
void endToEnd_givenUserSettingSingleTon_shouldReturnSingleton() {
UserSetting userSetting = UserSetting.getInstance();
userSetting.setFontSize(15);
userSetting.setTheme("dark");
assertEquals(15, userSetting.getFontSize());
assertEquals("dark", userSetting.getTheme());
UserSetting userSetting2 = UserSetting.getInstance();
assertEquals("dark", userSetting2.getTheme());
}
}