自制Builder作业,分别实现了两层嵌套和多层嵌套#522
Merged
onlyliuxin merged 4 commits intoonlyliuxin:masterfrom Jul 25, 2017
Merged
Conversation
Contributor
|
点赞 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
2017编程提高第6节课(作业)
问题
自制Builder 创建xml 字符串
分析
这里的意思主要是把原来的设置属性的操作转变为链式调用的操作,让这个Builder更加直观,实现链式调用的关键在于原本返回值是
void,现在改成了返回自己,所以就可以在调用的基础上再次调用代码
接下来就简单了,首先是预先定义好的
TagNode类:这里面除了基本的
attribute和children之外,还有一个toXML方法是用来打印这个节点内容的然后就是我们的
TagNodeBuilder类了:这里面的关键点在于多了一个
public TagBuilder(String rootName, TagBuilder tagBuilder)的构造函数,用来在子结点中存储父结点的信息,方便我们在调用toXML()方法的时候可以递归调用到根节点的toXML()方法测试
写完了就简单测试一下
运行结果:
扩展
从代码可以看到,我们实际上只做了两层结点的生成,实际上我们应该需要做多层结点的,也就是儿子还有儿子的意思,但是我们如果想通过上面的代码生成,就会发现,我们根本没有办法识别子结点的嵌套关系,所以如果要实现多层嵌套关系,我们必须还要增加一个方法来表达本层节点结束的意思,这里我用一个
and()表示,代码如下:可以看到我在
end()中返回了父结点的构造器,这样就终止了继续添加子结点在当前结点上。测试
也是简单地测试了一下
运行结果: