Home  >  Article  >  Web Front-end  >  Thinking about JavaScript Polymorphism and Adapter Pattern

Thinking about JavaScript Polymorphism and Adapter Pattern

高洛峰
高洛峰Original
2016-11-22 10:07:031081browse

Without further ado, let’s start with a piece of code (reprinted from "JavaScript Design Patterns and Development Practices")

        //谷歌地图show方法
        var googleMap = {
            googlShow: function() {
                console.log("谷歌地图");
            }
        };
        //百度地图show方法
        var baiduMap = {
            baiduShow: function() {
                console.log("百度地图");
            }
        };
       //渲染地图函数
       var renderMap=function(map){
           if(map.show instanceof Function){
             map.show();        
          }
       };
       renderMap(googleMap);//输出:开始渲染谷歌地图
       renderMap(baiduMap);//输出:开始渲染百度地图

Regarding the questions raised in the book, it is assumed that the name of the method for displaying maps provided by each map API is show. In actual development Maybe it won't go so smoothly. The idea proposed by the author in the book is to use the adapter pattern to solve the problem. The following is what I improved after imitating the adapter pattern:

        var googleMap = {
            googlShow: function() {
                console.log("谷歌地图");
            }
        };
        var baiduMap = {
            baiduShow: function() {
                console.log("百度地图");
            }
        };
        
        //适配器参数配置
        var mapArg = {
            "googleMap": googleMap.googlShow,
            "baiduMap": baiduMap.baiduShow
        };
  
        //适配器地图
        var adaptMap = {
            show: function(arg) {
                for (var imap in mapArg) {
                    for (var fmap in arg) {
                        if (imap && fmap && mapArg[imap].name==fmap) {
                            return mapArg[imap]();
                        }
                    }
                }
            }
        };
        //只关注发出显示地图而不关注具体用哪种地图
        var renderMap = function(arg) {
            adaptMap.show(arg);
        };
        //当增加了搜搜地图,我们需要添加搜搜地图的方法以及修改适配器地图参数
        //而不需要对renderMap函数进行修改
        var sosoMap = {
            sosoShow: function() {
                console.log("搜搜地图");
            }
        };
        mapArg.sosoMap=sosoMap.sosoShow; 
        render(sosoMap);


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn