1

简单明了的体会构建者模式 - 乌托拉赛文

 1 year ago
source link: https://www.cnblogs.com/m78-seven/p/17234233.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

简单明了的体会构建者模式 - 乌托拉赛文 - 博客园

我们由一个小小的Demo来引出主题,尽管这个Demo有点长~~,我相信还是值得你一看的!

2150784-20230319203227450-244584461.png

木兰诗中有:“雄兔脚扑朔,雌兔眼迷离;双兔傍地走,安能辨我是雌雄?”

对象之间的比较想必大家都很熟悉。只须用 util 包中的Objects.equals()方法即可。如果我想找出对象之间不相同的属性呢?
那肯定是一个一个属性进行对象啊!
不错,的确是要一个一个的进行对象,然后找出不有差异的属性Key。

java
public class DiffTest {

    public static void main(String[] args) {
        Person wanger1 = new Person("王小二", 12);
        Person wanger2 = new Person("汪小二", 12);

        System.out.println(wanger1.diff(wanger2));
    }



    @Getter
    @Setter
    public static class Person implements Diffable<Person> {
        private String name;
        private Integer age;

        public Person() {}

        public Person(String name, Integer age) {
            this.name = name;
            this.age = age;
        }


        @Override
        public DiffResult<Person> diff(Person that) {
            return new DiffBuilder(this, that, ToStringStyle.NO_CLASS_NAME_STYLE)
                    .append("name", this.name, that.name)
                    .append("age", this.age, that.age)
                    .build();
        }
    }

}
  • 依赖的三方包
xml
  <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
  </dependency>

上面的Test借助了Diffable 这个接口来支持可以进行比对,(一般接口申明成 xxxable 代表着这个类支持某个功能,比如 JsonableComparable�...等)
那么 diff(T obj)方法 借用了 DiffBuilder 这个类来构建出比对后的结果,里面的写法展示了具体构建的过程。最后由build� 方法返回需要构建出的对象。

最上层的接口非常的简单!(定义接口难道不是越简单越好?)

java
public interface Builder<T> {

    /**
     * Returns a reference to the object being constructed or result being
     * calculated by the builder.
     *
     * @return the object constructed or result calculated by the builder.
     */
    T build();
}

所以构建者模式,就是用代码构建一个对象,他演示了一个对象的构建过程,实现方法完全自己实现,我个人非常喜欢这种接口,给你一个白纸随你画,当然给你限定了T(总不定义一个狗但build一个猫出来吧!)。是不是和写作文一样,拟定好一个主题,然后围绕着主题发挥你的文采吧!

那么通过本文你可以学习到以下知识点

  • 如何找出对象之间的差异(分辨出雌雄兔子)
  • 构建者的上层接口及实际用法之一

__EOF__

本文作者: Savey 本文链接: https://www.cnblogs.com/m78-seven/p/17234233.html 关于博主: 评论和私信会在第一时间回复。或者直接私信我。 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处! 声援博主: 如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK