一、工厂模式
//方式一 : 一次只能创建一个对象
//缺点 : 创建多个同类对象时,代码会重复
var obj = {
"sname":"jack",
"study" :function(){
console.log("学习ing");
}
};
var obj2 = new Object();
obj2.sname = "lily";
obj2.study = function(){
console.log( "学习ing" );
}
工厂模式
function student(name, age) {
var obj = new Object()
obj.name = name
obj.age = age
return obj
}
var stu1 = student('xiao li', 18)
var stu2 = student('xiao yuan', 18)
console.log( stu1 instanceof Object ) // true
二、单例模式
function Animal(name){
this.name = name;
}
var a1 = new Animal("小白");
var a2 = new Animal("大白");
console.log( a1 == a2 ); // false
要求 : a1 == a2 返回true 单例模式
function Student() {
if (!Student.instance) {
Student.instance = {
age: 3,
name: 'xiao',
}
}
return Student.instance
}
var s1 = new Student()
s1.age += 4
var s2 = new Student()
console.log(s1 == s2) // true
console.log(s2.age) // 7
三、代理模式
function Mx(){
this.sing = function(){
console.log( "可以开演唱会..." );
}
}
function Jjr(){
this.sing = function(money){
if( money >= 200000000 ){
//通知主人 可以开演唱会啦
new Mx().sing();
}
}
}
var jj = new Jjr();
jj.sing( 200000001 );
四、适配器模式
function Ipad(){
this.music = function(){
console.log( "ipad可以播放音乐" );
}
}
//定义一个适配器 判读产品功能
function Adapter(pro){
this.pro = pro;//某个商品
this.music = function(){
if( this.pro.music ){
console.log("可以播放音乐")
}else{
console.log("不可以播放音乐")
}
}
this.phone = function(){
if( this.pro.phone ){
console.log("可以打电话")
}else{
console.log("不可以打电话")
}
}
}
var ipad = new Ipad();
var adapter = new Adapter(ipad);
adapter.music(); // 可以播放音乐
adapter.phone(); // 不可以打电话
五、策略模式
function Child(dad,mum){
this.dad = dad;
this.mum = mum;
this.cry = function(){
//小孩哭了 通知 爸爸 开始冲奶了
this.dad.weinai();
}
//观察者模式(异步现象)
setTimeout( function(){
this.cry();
}.bind(this),Math.random()*5000+200 )
}
function Dad(){
this.weinai = function(){
console.log( "开始给孩子喂奶了" );
}
}
var dad = new Dad();
var ch = new Child(dad , null);// 3s后 -> 开始给孩子喂奶了
六、发布订阅模式和观察者模式
class EventEmitter {
constructor() {
this.subs = Object.create(null)
}
// { 'click': [fn1, fn2], 'change': [fn] }
$on(eventType, handler) {
this.subs[eventType] = this.subs[eventType] || []
this.subs[eventType].push(handler)
}
$emit(eventType) {
if (this.subs[eventType].length) {
this.subs[eventType].forEach(handler => {
handler()
})
}
}
}
// 测试
let em = new EventEmitter()
em.$on('click', () => {
console.log('click1') // click1
})
em.$on('click', () => {
console.log('click2') // click2
})
em.$on('fn', ()=> {
console.log('fn') // fn
})
em.$emit('click')
em.$emit('fn')
七、观察者模式
class Dep {
constructor() {
this.subs = []
}
addSub(sub) {
if (sub && sub.update) {
this.subs.push(sub)
}
}
notify() {
console.log('this.subs-->', this.subs)
this.subs.forEach(sub => {
sub.update()
})
}
}
class Watcher {
update() {
console.log('update')
}
}
let dep = new Dep()
let watcher1 = new Watcher()
console.log(watcher1)
let watcher2 = new Watcher()
dep.addSub(watcher1)
dep.addSub(watcher2)
dep.notify() // update -> 2次