当前位置: 移动技术网 > IT编程>软件设计>设计模式 > Matlab模板模式

Matlab模板模式

2019年05月23日  | 移动技术网IT编程  | 我要评论

在模板模式(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

  

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网