js设计模式

19.设计模式(csdn)

1.单例模式

方式一:

   // 写法1 
        class Singleton {
            constructor() {
            }
        }
        // 闭包的模式
        Singleton.getInstance = (function () {
            let instance;
            return function () {
                if (!instance) {
                    instance = new Singleton()
                }
                return instance
            }
        })();
        var s1 = new Singleton.getInstance()
        var s2 = new Singleton.getInstance()
            console.log(s1 == s2);//true

方式二:

  // 写法2 静态方法new实例
        class Person{
            static getInstance(){
                if (!Person.instance) {
                    Person.instance=new Person()
                }
                return Person.instance
            }
        }
        var p1=Person.getInstance()
        var p2=Person.getInstance()
        console.log(p1==p2);//true

单例模式对话框案例

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <style>
        .dialog {
            width: 500px;
            height: 350px;
            border: 1px solid #000;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            display: none;
        }

        .header {
            height: 40px;
            display: flex;
            background-color: #ccc;
            justify-content: space-between;
            align-items: center;
            line-height: 40px;
        }

        .close {
            width: 50px;
            height: 40px;
            background-color: orange;
            text-align: center;
            line-height: 40px;

        }
    style>
head>

<body>
    
    <script>
        class Dialog {
            constructor() {
                this.el = null
                this.el = document.createElement("div")
                this.el.className = "dialog"
                let strHTML = `
                
标题
关闭
`
this.el.innerHTML = strHTML document.body.appendChild(this.el) this.close() } // init() { // this.el = document.createElement("div") // this.el.className = "dialog" // let strHTML = ` //
//
标题
//
关闭
//
//
// ` // this.el.innerHTML = strHTML // document.body.appendChild(this.el) // this.close() // } show(options){ this.el.style.display="block" this.el.querySelector(".title").innerHTML=options.title } hide(){ this.el.style.display="none" } close(){ let self=this this.el.addEventListener("click",function(e){ if (!e.target.className=="close") { return } self.hide() }) } } Dialog.getInstance = (function () { let instance return function () { if (!instance) { instance = new Dialog() // instance.init() } return instance } })() new Dialog.getInstance() new Dialog.getInstance().show({ title:"小小易啊" }) setTimeout(function(){ new Dialog.getInstance().hide() },5000)
script> body> html>

2.工厂模式

    // 工厂模式1
        function animal(o) {
            var obj = new Object()
            obj.name = o.name
            obj.age = o.age
            return obj
        }
        var cat = animal({ name: "cat", age: 2 })
        var dog = animal({ name: "dog", age: 2 })
        // 工厂模式2
        class Man {
            getName() {
                console.log("男");
            }
        }
        class Woman {
            getName() {
                console.log("女");
            }
        }
        class Factory {
            static create(type) {
                switch (type) {
                    case Man.name:
                        return new Man()
                        break;
                    case Woman.name:
                        return new Woman()
                        break;
                    default:
                        break;
                }
            }
        }
        var m=Factory.create("Man")
        m.getName()//男
        var w=Factory.create("Woman")
        w.getName()//女

3.构造者模式

 // 构造器模式1
        function car(color, speed, price) {
            this.color = color
            this.speed = speed
            this.price = price
            this.showColor = function () {
                console.log(this.color);
            }
        }
        var c = new car("yellow", "200", 500)
        c.showColor()
        // 构造器模式2
        // 1.产品
        class Computer{
            constructor(name,cpu,memory,storage){
                this.name=name
                this.cpu=cpu
                this.memory=memory
                this.storage=storage
            }
        }
        // 2.构造产品的工厂
        class ComputerBuilder{
            setName(name){
                this.name=name
                return this
            }
            setCpu(num){
                this.cpu=num
                return this
            }
            setMemory(num){
                this.memory=num
                return this
            }
            setStorage(num){
                this.storage=num
                return this
            }
            builder(){
                return new Computer(this.name,this.cpu,this.memory,this.storage)
            }
        }
        // 3.给别人传参数,他帮我们找产品
        let pc=new ComputerBuilder()
        .setName("华为")
        .setCpu("I9")
        .setMemory("16G")
        .setStorage("2T")
        console.log(pc);

4.订阅者模式

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <style>
        .box {
            width: 200px;
            height: 200px;
            border: 1px solid #000;
        }
    style>
head>

<body>
    <div class="box box1">
        <button>发送消息button>
    div>
    <div class="box box2">
        <button id="no">拒绝接收button>
        <div class="msg">div>
    div>
    <div class="box box3">
        <div class="msg">div>
    div>
    <script>
        // 把一个个div,理解为一个个组件,组件之间通信可以使用订阅者模式
        const obServer = {
            list: {},
            $on(event, callback) {
                // 如果指定的属性名称不存在,就给他一个空数组
                if (this.list[event] == undefined) {
                    this.list[event] = []
                }
                this.list[event].push(callback)
            },
            $off(event, callback) {
                if (this.list[event] == undefined) {
                    return
                }
                // 拿着传入的函数,去指定的数组里面找,并且返回下标
                let index = this.list[event].findIndex((item) => {
                    item == callback
                })
                if (index == -1) {
                    return
                }
                this.list[event].splice(index, 1)
            },
            $emit(emit, o) {
                // 判断是否有值,没有就终止
                if (!this.list[event]) {
                    return
                }
                // 有就遍历
                this.list[event].forEach(item => {
                    item.call(null, o)
                });
            }
        }
        var oBtn = document.querySelector("button")
        var oMsg = document.querySelectorAll(".msg")
        oBtn.onclick = function () {
            obServer.$emit("send", "我发送消息")
        }
        const fn1 = (str) => {
            oMsg[0].innerHTML = str
        }
        obServer.$on("send", fn1)
        const fn2 = (str) => {
            oMsg[1].innerHTML = str
        }
        obServer.$on("send", fn2)
        // 解绑
        var no = document.querySelector("#no")
        no.onclick = function () {
            obServer.$off("send", fn1)
        }
    script>
body>

html>

5.代理模式

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
head>

<body>
    <script>
        const oImage = (function () {
            // 自执行函数,默认执行,就创建一个图片,并且添加到页面上
            var oImg = document.createElement("img")
            document.body.appendChild(oImg)
            return {
                setSrc(url) {
                    oImg.src = url
                }
            }
        })()
        // 2.代理
        const proxyImage = (() => {
            // 1.创建一个img对象
            const img = new Image()
            // 2.给img设置url路径,就会去加载,如果加载成功,就会执行onload事件
            img.onload = function () {
                // 有效图片
                oImage.setSrc(this.src)
            }
            return {
                setSrc(url) {
                    oImage.setSrc("./img/loading.gif")
                    img.src = url
                }
            }
        })()
        // 代理操作
        proxyImage.setSrc("https://img1.baidu.com/it/u=3320660778,1222820597&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=734")
    script>
body>

html>

6.装饰器模式

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
head>

<body>
    <script>
        // 装饰器模式:不破坏原来的代码,可以对原来的代码进行功能'增强'
        function oldFunction() {
            console.log("我是老的方法");
        }
        var _oldFunction = oldFunction
        function newFunction() {
            _oldFunction()
            console.log("我是新添加的方法");
        }
        oldFunction()
        newFunction()

        // ES6类的实现装饰器模式
        class OldFunction {
            show() {
                console.log("我是老的方法类");
            }
        }
        // 装饰器
        class Decorator {
            constructor(cls) {
                this.oldCls = cls
            }
            newFunction(){
                console.log("我是新添加的方法类");
            }
            show(){
                this.newFunction()
                this.oldCls.show()
            }
        }
        new Decorator(new OldFunction).show()
    script>
body>

html>

7.策略模式

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
head>

<body>
    <script>
        // 规则对象
        const Rules = {
            "A": function (num) {
                return num * (1 + 0.9)
            },
            "B": function (num) {
                return num * (1 + 0.6)
            },
            add(level, callback) {
                this[level] = callback
            },
            remove(level) {
                if (this[level]) {
                    delete this[level]
                }
            }
        }
        // 使用规则
        function useCalcRules(level, num) {
            //如果规则,可以执行
            if (Rules[level]) {
                return Rules[level].call(null, num)
            }
        }
        console.log(useCalcRules("A",1000));
        // 定义规则
        const fn1 = function (num) {
            return num * 0.01
        }
        // 添加规则
        Rules.add("F", fn1)
        // 使用规则
        console.log(useCalcRules("F",1000));
    script>
body>

html>

8.适配器模式

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
head>
<body>
    <script>
        class PluginA{
            getName(){
                console.log("我是插件A");
            }
        }
        class PluginB{
            getName(){
                console.log("我是插件B");
            }
        }
        class Target{
            constructor(Plugin){
                this.plugin=new Plugin
                console.log(this);
                
            }
            getName(){
                this.plugin.getName()
            }
        }
        new Target(PluginA).getName()
        new Target(PluginB).getName()
    script>
body>
html>

你可能感兴趣的:(javascript,设计模式,前端)