标签:const 控制 orm get function new info 特性 cti
系统中被唯一使用
一个类只有一个实例
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 SingletonPatternDemo {
public static void main(String[] args) {
//不合法的构造函数
//编译时报错:构造函数SingleObject()不可见!!!
//SingleObject object = new SingleObject();
//获取唯一可用的对象
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
}
})()
// 无法控制
let obj1 = SingleObject.getInstance()
obj1.login()
let obj2 = SingleObject.getInstance()
obj2.login()
console.log(obj1 === obj2)
//------------------------------------------
let obj4 = SingleObject.getInstance()
obj4.login()
let obj5 = new SingleObject()
obj5.login()
console.log(obj4 === obj5)// false
//jQuery 只有一个 '$'
if (window.jQuery != null) {
return window.jQuer
}else {
//初始化......
}
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 = (function () {
let instance
return function () {
if (!instance) {
instance = new LoginForm();
}
return instance
}
})()
// 一个页面中调用登录框
let login1 = LoginForm.getInstance()
login1.show()
// login1.hide()
// 另一个页面中调用登录框
let login2 = LoginForm.getInstance()
login2.show()
// 两者是否相等
console.log('login1 === login2', login1 === login2)
标签:const 控制 orm get function new info 特性 cti
原文地址:https://www.cnblogs.com/ygjzs/p/12238557.html