Code Fragment-封装重复代码的代码

封装重复代码的方法有:

  1. 提取方法:在一个类里提取重复部分的code生成方法,在其他使用的地方直接调用。
  2. pull up方法:把两个兄弟类中重复的方法,放到父类中实现。
  3. 提取成类:使用组合的方法。
  4. 封装成静态的工具类。
  5. 使用单例。
  6. 重载类型的方法,参数少的去调用参数多的,在多出的参数里传入默认值。

可以使用Thymeleaf的Fragment封装重复代码Fragment是一种可重用的片段,可以在HTML中定义,然后在其他HTML中通过th:insert或th:replace标签来引用。 可以创建一个工具类,其中包含一个静态方法,该方法接受一个Thymeleaf上下文和一个片段名称作为参数,并返回一个字符串,该字符串包含通过th:insert或th:replace标记引用片段的HTML代码。 例如,下面是一个可能的实现: ```java public class ThymeleafUtils { public static String getFragment( IContext context, String fragmentName ) { final String template = "[[${fragmentName}]]"; final IStandardFragment fragment = StandardFragmentProcessor.findAndProcess( context, template ); final StringWriter writer = new StringWriter(); try { fragment.writeTo( writer ); } catch (IOException e) { // handle exception } return writer.toString(); } } ``` 然后,可以在Thymeleaf模板中使用这个工具类来封装重复代码。例如,假设有一个头部和底部是重复的布局,可以这样使用: ```html <!-- header fragment --> <div th:fragment="header"> <header> <!-- header content goes here --> </header> </div> <!-- footer fragment --> <div th:fragment="footer"> <footer> <!-- footer content goes here --> </footer> </div> <!-- page template --> <html> <head> <title>My Page</title> </head> <body> <!-- include header fragment --> [[# th:replace="${@thymeleafUtils.getFragment(context, 'header')}" /]] <main> <!-- page content goes here --> </main> <!-- include footer fragment --> [[# th:replace="${@thymeleafUtils.getFragment(context, 'footer')}" /]] </body> </html> ``` 这样,就可以在不重复编写头部和底部的情况下,将它们包含在每个页面中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值