设计模式学习-(11.桥接模式)

桥接模式: 提取需求的共同点,在这里关键是脱离与this的耦合


// 提取共同点
    function changeColor( dom ,color ,bg){
        dom.style.color = color;
        dom.style.background = bg;
    }

    var spans = document.getElementsByTagName('span');
    spans[0].onmouseover = function () {
        changeColor( this, 'red' , '#ddd' );
    };
    spans[0].onmouseout = function () {
        changeColor( this, '#333' , '#df5f5f5' );
    };

    spans[1].onmouseover = function () {
        changeColor( this.getElementsByTagName('strong')[0], 'red' , '#ddd' );
    };
    spans[1].onmouseout = function () {
        changeColor( this.getElementsByTagName('strong')[0], '#333' , '#df5f5f5' );
    };

 //  多元化对象,  与建造者模式类似,只不过 分类 并没有用闭包的方式实现

function Speed( x,y ){
        this.x = x;
        this.y = y;
    }
    Speed.prototype.run = function () {
        console.log( '运动起来' );
    };

    function Color( cl ){
        this.color = cl;
    }
    Color.prototype.draw = function () {
        console.log( '绘制色彩' );
    };

    function Ball( x, y ,c ){
        this.speed = new Speed( x, y );
        this.color = new Color( c );
    }
    Ball.prototype.init = function () {
        this.speed.run();
        this.color.draw();
    };
    var ball = new Ball( 1 , 2, 3 );
    ball.init();


猜你喜欢

转载自blog.csdn.net/zxf13598202302/article/details/79473940
今日推荐