js或者java设计模式代码示例

  • 访问者设计模式:如果一个对象的部分操作非常容易改变,那么就将这部分代码封装成一个单独的类,同时将原始对象传给它,这样就可以在需要改变的时候新增一个访问者就可以了。

    
    function  element(visiter){
        this.name = "xxxxx";
        this.visiter = visiter;     
    }
    element.prototype.visite = function(){
            this.visiter.visite(this);
    }
    function visiter(){}
    visiter.prototype.visite = function(element){
            console.log(element.name);
    }
    let vis = new visiter();
    let ele = new element(vis);
    ele.visite();
  • 中介者设计模式:如果一个对象的操作会引起其它相关对象的变化,而这个对象又不希望自己来处理这些关系,那么就可以找中介者,比如”多人聊天-聊天室就是中介者”,”多人打游戏-游戏的控制就是中介者”

    function seller(agency,name){
    this.name = name;
    this.agency = agency;
    }
    seller.prototype.sellHouse = function(){
        this.agency.sellHouse(this.name);
    }
    seller.prototype.registe = function(){
        this.agency.registe(this,"seller");
    }
    seller.prototype.receiveMessage = function(message){
        console.log(this.name,"听中介说:",message,"买房子");
    }
    function buyer(agency,name){
        this.agency = agency;
        this.name = name;
    }
    buyer.prototype.buyHouse = function(){
        this.agency.buyHouse(this.name);
    }
    buyer.prototype.registe = function(){
        this.agency.registe(this,"buyer");
    }
    buyer.prototype.receiveMessage = function(message){
        console.log(this.name,"听中介说:",message,"卖房子");
    }
    function agency(){}
    agency.prototype.sellHouse = function(message){
        for(let i =0,len = this.buyers.length;i<len;i++){
            this.buyers[i].receiveMessage(message);
        }
    }
    agency.prototype.buyHouse = function(message){
        for(let i =0,len = this.sellers.length;i<len;i++){
            this.sellers[i].receiveMessage(message);
        }
    }
    agency.prototype.registe = function(element,type){
        if(!this.sellers){
            this.sellers = [];
        }
        if(!this.buyers){
            this.buyers = [];
        }
        if(type == "buyer"){
            this.buyers.push(element);
    
        }else if(type == "seller"){
            this.sellers.push(element);
        }   
    }
    let agent = new agency();
    let buyer1 = new buyer(agent,"买家一");
    buyer1.registe();
    let buyer2 = new buyer(agent,"买家二");
    buyer2.registe();
    let seller1 = new seller(agent,"卖家一");
    seller1.registe();
    let seller2 = new seller(agent,"卖家二");
    seller2.registe();
    
    buyer1.buyHouse();
    seller1.sellHouse();    
  • 责任链设计模式

    
        function  node(handleFun){
        this.handleFun = handleFun;
        }
        node.prototype.setNextNode = function(nextNode){
            this.nextNode = nextNode;
        }
        node.prototype.do = function(money){
            if(this.handleFun(money) == "error" && this.nextNode){
                this.nextNode.do(money);
            }
        }
        node.prototype.doNext = function(money){//存在异步处理时主动调用的
            this.nextNode && this.nextNode.do(money);
        }
    function employee(money){
        let self = this;
        let innerFun = function(){
                if(money < 200){
                console.log("职员处理了");
            }
            self.doNext(money);//异步处理
        }
        setTimeout(innerFun,1000);
    
    }   
    function manager(money){
        if(money<400){
            console.log("经理处理了");
            return "success";
        }
        return "error";
    }
    function boss(money){
        console.log("boss 处理了");
    }
    let employeeNode = new node(employee);
    let managerNode = new node(manager);
    let bossNode = new node(boss);
    employeeNode.setNextNode(managerNode);
    managerNode.setNextNode(bossNode);
    employeeNode.do(300);
  • js单例设计模式

    
     function createSingleFactory(createFun){
        let single = null;
        return function(){
            return single || (single = createFun());
        }
    }
    function add(){
        return {
            name:"add"
        }
    }
    let singleAddFun = createSingleFactory(add);
    let add1 = singleAddFun();
    let add2 = singleAddFun();
    console.log(add1 == add2);//true
  • js代理设计模式

    
    //被代理“对象(所以直接执行方法返回对象)”;提供方法给代理"对象"
    let myImage = (function(){
        let imageNode = document.getElementById("img");
        document.body.appendChild(imageNode);
        return {
            setSrc:function(src){
            imageNode.src = src;
        }
        }
    });
    //代理对象:操控被代理对象
    var proxyImage = (function(){
        let img = new Image();
        img.onLoad = function(){
            myImage.setSrc(this.src);
        }
        return {
            setSrc:function(src){
                myImage.setSrc("http://loading.img");
                img.src = src;
            }
        }
    });
    proxyImage.setSrc("http://real.img");
  • 观察者设计模式:主要是要有一个”被观察者对象”,当这个对象发生某种变化时触发观察者的调用

    //被观察者对象
    let obj = {
        eventList:{},
        registe:function(key,fn){
            if(!this.eventList[key]){
                this.eventList[key] = [];   
            }
            this.eventList[key].push(fn);
        },
        trigger:function(key,changedProperty){
            let fns = this.eventList[key];
            for(let i = 0,len=fns.length;i<len;i++){
                fns[i] (changedProperty);
            }   
        },
        remove:function(key,fn){//函数是可以和函数比较的(记住)
            let fns = this.eventList[key];
            if(!fns || fns.length == 0) return;
            for(let len = fns.length,i = len;i>=0;i--){
                if(fn == fns[i]){
                    fns.splice(i,1);
                }   
            }   
        }
    };
    //剩下只需要用listen来绑定事件,用trigger来触发事件就行了。
    
    //另外还可以 通过Object.assign来将上面的obj复制到任何一个对象上,使对象拥有被观察的资格
  • 命令设计模式

    let btn1 = document.getElementById("add");
    concatCommand = function(obj,command){
         obj.onclick = function(){
             command.execute();
         }
     }
    function command(handleFun){
         this.handleFun = handleFun;
     }
    command.prototype.execute = function(){
            this.handleFun();
    }
    function handleFun =function () {console.log("对于命令执行操作");}
    let commandOne = new command(handleFun);
    setCommand(btn1,handleFun);
    
    //在Java中感觉需要一个命令接口和子类,一个调用命令的对象,只需要在该对象中保持命令的属性应该就行了
  • java桥接设计模式:把一个对象变化的部分从主体分离出去,从而将多个维度的变化彻底分离,然后在主体对象中保持分离出去的引用,感觉该模式和访问者设计模式的主要区别是访问者是查看该对象,而该模式抽离出去的东西本身是属于该对象的一部分。

    
        public abstract class CpuAbility{
            public String checkAbility();
        }
        public AmdCpu implements CpuAblity{
            public String checkAbility(){return "不怎么好"}
        }
        public IntelCpu implements CpuAbility{
            public String checkAbility(){return "比较好";}
        }
        public abstract class Computer{
            CpuAbility cpuInstance;
            public Computer(CpuAbility instance){
                this.cpuInstance = instance;
            }
            public String checkComputer();
        }
        public HuaShuoComputer implements Computer{
            public HuaShuoComputer(CpuAbility instance){
                super(instance);
            }
            public String checkComputer(){
                return "华硕电脑"+super.cpuInstance.checkAbility();
            }
        }
        //这样不管是电脑的好坏的其它因素,还是其它品牌的电脑,都可以很好的理解
  • java类构建器设计模式:主要用于类的属性很多,而且属性有必填,也有非必填的。

    
    public class OutClass{
        private final int property1;//必填
        private final int property2;
        private final int property3;
        private final int property4;
        private final int property5;
        public OutClass(Builder builder){
            this.property1 = builder.property1;
            //......(一样赋值进去)
        } 
        public static class Builder{
            private final int property1;
            private int property2 = 0;
            private final int property3 = 0;
            private final int property4 = 0;
            private final int property5 = 0;
            public Builder(int property1){
                this.property1 = property1;
            }
            //其它属性也像这样弄一下
            public Builder setProperty2(int property2){
                this.property2 = property2;
                return this;
            }
            public OutClass build(){
                return new OutClass(this);
            }
        }
    }
    //静态内部类是不需要依赖外部类实例的
    OutClass instance = new OutClass.Builder(21).setProperty1(32).build();
  • java通过枚举实现单例

    
    public enum SingleTonInstance{
        INSTANCE;//调用SingleTonInstance构造函数生成的实例
        private Resource instance;
        private SingleTonInstance(){//私有化构造方法
            instance = new Resource();
        }   
        public Resource getInstace(){//提供开口获得单例
            return instance;
        }
        public static void staticMethod(){
            return instance.toString();
        }
    }
    SingleTonInstance.INSTANCE.getInstance();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值