例1.シングルモード
class Msg{
constructor(){
this.ele = document.createElement("div");
document.body.appendChild(this.ele);
}
init(str){
this.ele.innerHTML = str;
}
}
var singleCase = (function(){
var instance;
return function(text){
if(!instance){
instance = new Msg();
}
instance.init(text);
return instance;
}
})();
// m1和m2显示的是在同一个盒子里
var m1 = singleCase("hello");
var m2 = singleCase("world");
console.log(m1===m2);//ture
2. Combinationモード
function computer(){};
computer.prototype.init = function(){
console.log("开电脑");
}
function phone(){};
phone.prototype.init = function(){
console.log("开手机");
}
function tv(){};
tv.prototype.init = function(){
console.log("开电视");
}
function zuhe(){
this.arr = [];
}
// 用来放所有的对象
zuhe.prototype.add = function(task){
this.arr.push(task);
}
// 当统计好所有对象后开始执行
zuhe.prototype.action = function(){
for(var i = 0;i<this.arr.length;i++){
this.arr[i].init();
}
}
var c = new zuhe();
c.add(new computer());
c.add(new phone());
c.add(new tv());
c.action();
3. Observerパターン
function Stu(n){
this.name = n;
this.type = function(){
if(Math.random() > 0.5){
return "学习";
}else{
return "睡觉";
}
}
}
function Teac(n){
this.name = n;
this.listen = function(t,sn){
if(t == "学习"){
console.log(`${sn}是好孩子`);
}else{
console.log(`给${sn}一巴掌`);
}
}
}
function Teac2(n){
this.name = n;
this.listen = function(t,sn){
if(t == "学习"){
console.log(`嗯嗯...点头离开`);
}else{
console.log(`把${sn}揪起来,叫家长`);
}
}
}
var s = new Stu("张三");
var t = s.type();
var t1 = new Teac("班主任");
t1.listen(t, s.name);
var t2 = new Teac2("教导主任");
t2.listen(t, s.name);