Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【JavaScript设计模式与开发实践】第一章-多态的运用 #51

Open
Kelichao opened this issue Jul 5, 2017 · 0 comments
Open

Comments

@Kelichao
Copy link
Owner

Kelichao commented Jul 5, 2017

1.26如何科学使用多态

  • 多态的最根本好处在于,你不必再向对象询问“你是什么类型”而后根据得到的答
    案调用对象的某个行为——你只管调用该行为就是了,其他的一切多态机制都会为你安
    排妥当。

普通写法

var googleMap = {
    show: function(){
    console.log( '开始渲染谷歌地图' );
    }
};
var baiduMap = {
    show: function(){
    console.log( '开始渲染百度地图' );
    }
};

// 函数以字符串形式的传参形式
// 如果判断条件一旦增多,就会变全是if-else语句
var renderMap = function( type ){
    if ( type === 'google' ){
        googleMap.show();
    }else if ( type === 'baidu' ){
        baiduMap.show();
    }
};

renderMap( 'google' ); // 输出:开始渲染谷歌地图
renderMap( 'baidu' ); // 输出:开始渲染百度地图

改进写法,多态适用于同种模式

var googleMap = {
    page: 10,
    show: function(){
        console.log( '开始渲染谷歌地图' );
    }
};
var baiduMap = {
    page: 1,
    show: function(){
        console.log( '开始渲染百度地图' );
    }
};

// 将render传入的参数换成相应的对象
var renderMap = function( map ){
    if ( map.show instanceof Function ){
        map.show();
        console.log(mape.page);
    }
};

renderMap( googleMap ); // 输出:开始渲染谷歌地图 10
renderMap( baiduMap ); // 输出:开始渲染百度地图 1
@Kelichao Kelichao changed the title 【《JavaScript设计模式与开发实践》第一章】 【《JavaScript设计模式与开发实践》】第一章 Jul 5, 2017
@Kelichao Kelichao changed the title 【《JavaScript设计模式与开发实践》】第一章 【JavaScript设计模式与开发实践】第一章-多态 Jul 5, 2017
@Kelichao Kelichao changed the title 【JavaScript设计模式与开发实践】第一章-多态 【JavaScript设计模式与开发实践】第一章-多态的运用 Aug 7, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant