Matlab模板模式

在模板模式(Template Pattern)中,一个抽象类公开定义了执行它的方法的方式/模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行。本文以数据库SQL语法为例来阐述模板模式的应用场景。由于不同的数据库SQL语法存在差异,在替换数据库时需要更改程序大量的SQL语句,而模板模式能够将零散的并且随数据库变化的SQL语句提取出来,提高了软件的可移植性和兼容性,本文依据http://www.w3school.com.cn/sql/sql_top.asp上面给出的语法,设计出了模板模式:

模板方法类:

classdef SQLTemplate < handle
    methods(Abstract,Access=protected)
        run_top_sql(obj,top_number,table_name);
    end   
    methods
        function run_top(obj,top_number,table_name)
            try
                obj.begin_conn();
                obj.begin_tran();
                obj.run_top_sql(top_number,table_name);
                obj.commit_tran();
            catch
                obj.rollback_tran();
            end
            obj.end_conn();
        end
        function begin_conn(~)
            disp('开启数据库连接');
        end
        function begin_tran(~)
            disp('开启事务');
        end
        function commit_tran(~)
            disp('提交事务');
        end
         function rollback_tran(~)
            disp('回滚事务');
        end
        function end_conn(~)
            disp('关闭数据库连接');
        end
    end
end

具体实现类--MySQL类:

classdef MySQL < SQLTemplate
     methods(Access=protected)
         function run_top_sql(~,top_number,table_name)
               disp(['select * from ',table_name,' limit ',num2str(top_number)]);
         end
    end  
end

具体实现类--Oracle类:

classdef Oracle < SQLTemplate
     methods(Access=protected)
         function run_top_sql(~,top_number,table_name)
               disp(['select * from ',table_name,' where ROWNUM <= ',num2str(top_number)]);
         end
    end  
end

具体实现类--SQLServer类:

classdef SQLServer < SQLTemplate
     methods(Access=protected)
         function run_top_sql(~,top_number,table_name)
               disp(['select top ',num2str(top_number),' * from ',table_name]);
         end
    end  
end

  

posted on 2019-05-22 15:29  sw-lab  阅读(555)  评论(0编辑  收藏  举报

导航