前端常用的几种设计模式

1.单例模式

			/* 			// 只是实例化一次,每次返回的实例都是同一对象、
			function SingleOne(name) {
				this.name = name;
			}

			// 静态方法,创建实例
			SingleOne.createInstance = function () {
				if (!this.instance) {
					this.instance = new SingleOne(name);
				}
				return this.instance;
			}; */

			// 只能new yici

			const SingleOnlyOne = (function () {
				//一个立即执行

				var instance;

				return function (name) {
					if (!instance) {
						if (new.target !== undefined) {
							// 确保是 new 执行
							this.name = name;
							instance = this;
						} else {
							throw Error("确保new 实例执行");
						}
					}

					return instance;
				};
			})();
			const a = new SingleOnlyOne("lisi");
			const b = new SingleOnlyOne("zsa");
			console.log(a, b, a === b);

2 策略模式
对应的方法由外面抽象,传入

		const levles = {
				s: function (salary) {
					return salary * 4;
				},
				d: function (salary) {
					return salary * 2;
				},
			};
			function calc(lev, salary) {
				return levles[lev](salary);
			}

			console.log(calc("s", 4));
			console.log(calc("d", 2));

2 发布订阅

			// 发布订阅  一对多的关系

			// 发布者

			// 缓冲列表,用来绑定回调函数

			// 当事件被触发的时候,依次执行缓冲列表中的回调函数

			const salesOffices = {};

			salesOffices.clientList = {};

			salesOffices.listen = function (type, fn) {
				if (this.clientList[type]) {
					this.clientList[type].push(fn);
				} else {
					this.clientList[type] = [fn];
				}
			};
			salesOffices.trigger = function () {
				let args = arguments;
				let type = Array.prototype.shift.call(args);
				let fns = this.clientList[type];
				fns.forEach((callback) => {
					callback.apply(this, args);
				});
			};

			salesOffices.off = function (type, fn) {
				let fns = this.clientList[type];
				let index = fns.findIndex((callback) => callback === fn);
				fns.splice(index, 1);
				console.log(this.clientList[type]);
			};

			// zs 只对 105
			const fn1 = function (price, daxiao) {
				console.log(`zs价格${price},面积${daxiao}`);
			};
			salesOffices.listen("105m", fn1);

			// lisi 只对 105
			const fn2 = function (price, daxiao) {
				console.log(`lisi价格${price},面积${daxiao}`);
			};
			salesOffices.listen("105m", fn2);

			// ww 只对 128
			const fn3 = function (price, daxiao) {
				console.log(`zs价格${price},面积${daxiao}`);
			};
			salesOffices.listen("128m", fn3);

			salesOffices.trigger("105m", 1700, 105);
			salesOffices.trigger("128m", 1800, 128);

			// 取消订阅

			// 取消zs 对105
			salesOffices.off("105m", fn3);

3责任链模式

		// 责任链模式  ,简单理解就是 一级一级的往下处理  绑定每一个下一级处理过程

		// 500充值 成功  获得50优惠
		//  200 充值成功 获得 20

		// 不充值根据随机来看是否获得 10元

		function get50By500(money, isPay) {
			if (money === 500 && isPay) {
				console.log("获得50优惠券");
			} else {
				return "nextErrorCallback";
			}
		}
		function get20By200(money, isPay) {
			if (money === 200 && isPay) {
				console.log("获得20优惠券");
			} else {
				return "nextErrorCallback";
			}
		}
		function get10ByRandom(money, isPay) {
			if (Math.random() > 0.3) {
				console.log("恭喜获得10元优惠券");
			} else {
				console.log("没有获得优惠券");
			}
		}

		const Chain = function (fn) {
			this.fn = fn;
			this.nextErrorCallback = null;
		};

		Chain.prototype.setNextErrorCallback = function (nextErrorCallback) {
			return (this.nextErrorCallback = nextErrorCallback);
		};

		Chain.prototype.passRequest = function () {
			var res = this.fn.apply(this, arguments);
			if (res === "nextErrorCallback") {
				return (
					this.nextErrorCallback &&
					this.nextErrorCallback.passRequest.apply(
						this.nextErrorCallback,
						arguments
					)
				);
			}
			return res;
		};

		var chain500 = new Chain(get50By500);
		var chain200 = new Chain(get20By200);

		var chainRandom = new Chain(get10ByRandom);

		chain500.setNextErrorCallback(chain200);
		chain200.setNextErrorCallback(chainRandom);
		// console.log(chain500);
		chain500.passRequest(500, true);
		chain500.passRequest(100, true)

4状态模式

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btn">开关</button>
  </body>
  <script>
    function Light(light) {
      this.light = light
      this.offState = new OffState()
      this.strongState = new StrongState()
      this.weakState = new WeakState()
      this.cuState = this.offState
    }

    Light.prototype.init = function () {
      this.light.onclick = () => {
        this.changeLight()
      }
    }
    Light.prototype.setState = function (newState) {
      this.cuState = newState
    }

    Light.prototype.changeLight = function () {
      // console.log(11);
      // this.btnPass
      this.cuState.btnPass(this)
    }

    class OffState {
      btnPass(that) {
        console.log('开灯,强光')
        // console.log('Light',Light);
        // console.log('that',that);
        that.setState(that.weakState)
      }
      // set
    }
    class WeakState {
      btnPass(that) {
        console.log('弱光')
        // console.log('Light',Light);
        // console.log('that',that);
        that.setState(that.strongState)
      }
      // set
    }
    class StrongState {
      btnPass(that) {
        console.log('关灯')
        that.setState(that.offState)
      }
      // set
    }

    const btnLight = new Light(document.getElementById('btn'))
    btnLight.init()
  </script>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值