JavaScript 代理模式

121 阅读1分钟

为其他对象提供一种代理以控制对这个对象的访问。

说到代理就少不了Nginx,Nginx就是通过代理让你通过一个地址访问到多个不同的服务,还能解决跨域访问的问题。

class HostName {
    constructor(host, port) {
        this.host = host
        this.port = port
    }
    
    getAddress() {
        return `${this.host}:${this.port}`
    }
}

class Nginx {
    constructor() {
        this.hostList = []
    }
    
    addHost(host) {
        this.hostList.push(host)
    }
    
    visitHostApi(api) {
        for(const item of this.hostList) {
            if(item.hasOwnProperty(api)) {
                item[api]()
                item.getAddress()
                break 
            }
        }
    }
}

const host1 = new HostName('host', 8000)
const host2 = new HostName('host', 9000)
const nginx = new Nginx()

host1.login = () => { console.log('登录') }
host2.logout = () => { console.log('注销') }

nginx.addHost(host1)
nginx.addHost(host2)

nginx.visitHostApi('login')
nginx.visitHostApi('logout')