标签:uml图 his returns void username ssd 验证 == form
单例模式
示例
类图
说明
public class SingleObject{
//注意,私有化构造函数,外部不能new,只能内部能new
private SingleObject(){}
//唯一被new出来的对象
private SingleObject instance = null;
//获取对象的唯一接口
public SingleObject getInstance(){
if(instance == null){
//只new一次
instance = new SingleObject();
}
return instance;
}
//对象方法
public void login(username,password){
System.out.println(‘login...‘);
}
}
//测试
public class SingleonPatternDemo{
public static void main(String[] args){
//获取唯一可用的对象
SingleObject object = SingleObject.getInstance();
object.login();
}
}
class SingleObject{
login(){
console.log(‘login……‘);
}
}
//静态方法
SingleObject.getInstance = (function(){
let instance;
return function(){
if(!instance){
instance = new SingleObject();
}
return instance;
}
})();
//测试:注意这里只能使用静态函数getInstance,不能new SingleObject()
let obj1 = SingleObject.getInstance();
obj1.login();
let obj2 = SingleObject.getInstance();
obj2.login();
console.log(‘obj1 === obj2‘,obj1 === obj2); //true
console.log(‘------无法完全控制等情况------‘);
let obj3 = new SingleObject(); //无法完全控制
obj3.login();
console.log(‘obj1 === obj3‘,obj1 === obj3); //false
场景
示例:模拟登录框
/**
* 单例模式示例:模拟登录框
*/
class LoginForm {
constructor() {
this.state = ‘hide‘;
}
show() {
if (this.state === ‘show‘) {
alert(‘已经显示‘);
return;
}
this.state = ‘show‘;
console.log(‘登录框已显示‘);
}
hide() {
if (this.state === ‘hide‘) {
alert(‘已经隐藏‘);
return;
}
this.state = ‘hide‘;
console.log(‘登录框已经隐藏‘);
}
}
LoginForm.getInstance = (() => {
let instance;
return () => {
if (!instance) {
instance = new LoginForm();
}
return instance;
}
})();
//测试
let login1 = LoginForm.getInstance();
login1.show();
let login2 = LoginForm.getInstance();
login2.show();
console.log(‘login1 === login2‘,login1 === login2); //true
设计原则验证
标签:uml图 his returns void username ssd 验证 == form
原文地址:https://www.cnblogs.com/mrtransition/p/13902856.html