JS的设计模式与常规笔试题

本文介绍了JavaScript中的几种设计模式,包括工厂模式用于创建对象,单例模式确保类只有一个实例,装饰者模式用于扩展功能而不修改代码,策略模式解决复杂的if-else逻辑,代理模式作为请求的转发,以及发布订阅模式和迭代器模式的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工厂模式?

工厂是创建型模式,它的作用就是创建对象;

你想生成一个班级的40个学生,每个学生都有姓名、年龄等特征。这时候你创建一个“工厂”,把信息丢到工厂里,工厂就给你造一个人出来,非常方便。


//将创建对象的代码封装在一个函数中
function createPerson(name, age, gender) {
  var person = new Object();
  person.name = name;
  person.age = age;
  person.gender = gender;
  person.sayName = function () {
    console.log(this.name);
  }
  return person;
}
//利用工厂函数来创建对象
var person1 = createPerson("zhangsan", 18, 'male');
var person2 = createPerson("lisi", 20, 'female');

单例模式?

单例模式也称为单体模式,保证一个类仅有一个实例,并提供一个访问它的全局访问点

全局对象是最简单的单例模式,利用ES6的let不允许重复声明的特性,刚好符合这两个特点


// 单例设计模式的实现:面向对象
let Singleton = function(name) {
  this.name = name;
  this.instance = null;
}
Singleton.prototype.getName = function(){
  return this.name;
}
Singleton.getInstance = function(name) {
  if(!this.instance) {
    this.instance = new Singleton(name);
  }
  return this.instance;
}

let instance1 = Singleton.getInstance('why');
let instance2 = Singleton.getInstance('www');
console.log(instance1===instance2); // 输出true

let obj1 = new Singleton('why');
let obj2 = new Singleton('www');
console.log(obj1.getName());        // 输出why
console.log(obj2.getName());        // 输出www





// 单例设计模式的实现:闭包
let Singleton = function(name) {
  this.name = name;
}
Singleton.prototype.getName = function() {
  return this.name;
}
Singleton.getInstance = (function() {
  let instance = null;
  return function(name) {
    if(!instance) {
      instance = new Singleton(name)
    }
    return instance;
  }
})()

let instance1 = Singleton.getInstance('why');
let instance2 = Singleton.getInstance('www');
console.log(instance1 === instance2); // 输出true


装饰者模式?

在不改变原有函数代码的情况下,添加新的功能。


// 装饰者模式 
// 不改变对象自身代码的基础上新增功能
let a = ()=>{
    console.log('a');
}
// 开闭原则  
// let newa = ()=>{
//     console.log('a');
//     console.log('b');
// }

// newa();

let newa = ()=>{
    a();
    console.log('b');
}
// newa()
// 飞机大战  发射普通子弹   发射导弹   发射原子弹

function Plane() {

}
Plane.prototype.fire = function () {
    console.log('普通子弹');
}

function  MissileDecorator(plane) {
    this.plane = plane;
}

MissileDecorator.prototype.fire = function () {
    this.plane.fire();
    console.log('导弹');
}

function AtomDecorator(plane) {
    this.plane = plane;
}

AtomDecorator.prototype.fire = function () {
    this.plane.fire(); // 普通子弹 导弹 
    console.log('原子弹');
}

let plane = new Plane();
plane = new MissileDecorator(plane);
plane = new AtomDecorator(plane)
plane.fire();

策略模式?

可以有效的解决if else逻辑复杂,不可维护的弊端


// 策略模式   有效的解决if else 逻辑复杂不可维护的情况
// s a b c d  
// 5 4 3 2 1
// a   b 
let strategys = {
    s(base){
      console.log('女朋友');
      console.log('iphone');
      return base*5;   
    }, 
    a(base){
      console.log('书包');
      return base*4;   
    },
    b(base){
        return base*3;   
    }, 
    c(base){
        return base*2;   
    },
    d(base){
        return base;   
    },
    e(base){
       return 0;
    }
}

function catulateBonus(base,grade){
    return strategys[grade](base)
}






// function catulateBonus(base,grade){
//     if(grade==='s'){
//       console.log('女朋友');
//       console.log('iphone');
//       return base*5;
//     }else if(grade==='a'){
//       console.log('书包');
//       return base*4;
//     }else if(grade==='b'){
//       console.log('对联');
//       return base*3; 
//     }else if(grade==='c'){
//       return base*2; 
//     } else if(grade==='d'){
//       return base*1; 
//     } else {
//       return 0; 
//     }
// }
// // 老王 
// const result  = catulateBonus(1000,'s');
// console.log(result);
// // 小明
// const resulta  = catulateBonus(2000,'a');
// console.log(resulta);

代理模式?

主要做的是一层转发,可以理解成媒婆介绍男女对象


// 代理模式   转发请求
// 情景剧: 梁山伯与祝英台的故事
// 梁山伯把玫瑰送给媒婆 并委托替他向祝英台表白
// 鲜花
function Flower(owner,name) {
  this.owner = owner;
  this.name = name;
}
// 主角: 梁山伯
let liangShanbo = {
    sendFlower(target){
        let flower = new Flower('liangShanbo','rose');
        target.receiveFlower(flower);
    }
}
// 二号主人公: 媒婆   
let matchMaker = {
    receiveFlower(flower){
        zhuYingTai.receiveFlower(flower)
    }
}
// 女主角: 祝英台
let zhuYingTai = {
   receiveFlower(flower){
      console.log(`zhuYingTai receive ${flower.name} from ${flower.owner}`);
   }
}

// 梁山伯把玫瑰送给媒婆 并委托替他向祝英台表白
liangShanbo.sendFlower(matchMaker);

发布订阅模式?(观察者模式)
  1. 最基础的发布订阅者就是添加事件监听

  1. 就是比如买手机,需要有一个队列, 需要往队列中push数据, 再通过发布告知队列中的每一条数据


// 顾客购买iphone13
class Apple{
    constructor(){
        this.queue = []
    }
    push(obj){
        this.queue.push({
            name:obj.name,
            fn:obj.fn,
        })
    }
    publish(){
        this.queue.forEach((item)=>{
            item.fn(item.name)
        }) 
    }
}

const apple = new Apple();

apple.push({
   name:"freemen",
   fn(name){
      console.log(`${name} receive iphine13`);
      console.log(`真香!`);
   }
})

apple.push({
    name: "vinko",
    fn(name){
       console.log(`${name} receive iphine13`);
       console.log(`太香了!`);
    }
 })

apple.publish();


迭代器模式?

forEach就是

倒序迭代器


// 迭代器模式

const array = [1,2,3,4,5];

// forEach  迭代器模式 最基础应用
// array.forEach((item,index)=>{
    // console.log(`item:${item}`);
    // console.log(`index:${index}`);
// })

// 倒序迭代器
let reverseEach = function (obj,callback) {
    if(!Array.isArray(obj)){
        throw Error('params is must an array!')
    }
    for (let i = obj.length-1; i>=0; i--) {
        callback.call(obj[i],obj[i],i)
    }
}

reverseEach(array,(item,index)=>{
    console.log(`item:${item}`);
    console.log(`index:${index}`);
})




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值