JAVA03-Builder设计模式和模板模式

设计模式之Builder模式

解决了一个类参数过多,而导致的构造器参数 太长,或构造器太多的问题

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
  public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person(String name) {
        this(name, 19);
    }

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

/**
 * Builder模式
 * 1. 和目标类同样的属性
 * 2. 私有构造器(不是必须)
 * 3. 静态工厂方法(不是必须)
 * 4. 一个属性一个设置方法,该方法返回自身this
 * 5. 通过build方法将收集到的方法都设置到目标类中,并返回目标类
 */
public final class PersonBuilder {
    private int age;
    private String name;

    private PersonBuilder() {
    }

    // 静态工厂方法
    public static PersonBuilder aPerson() {
        return new PersonBuilder();
    }

    public PersonBuilder withAge(int age) {
        this.age = age;
        return this; // Builder模式的要点是返回自己 this
    }

    public PersonBuilder withName(String name) {
        this.name = name;
        return this; // Builder模式的要点是返回自己 this
    }

    // 最后通过build方法将参数设置到Person类中并返回
    public Person build() {
        Person person = new Person(name);
        person.setAge(age);
        return person;
    }
}

设计模式之模版方法模式,该模式依赖继承

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
  public class Singer {
    /**
     * 这个方法就是模版方法,它规定了一套流程
     * 相当于提供了一个模版,实现了子类可以覆盖模版的全部或部分
     */
    protected void sing() {
        title();
        content();
        end();

    }

    protected void title() {
        System.out.println("一首儿歌");
    }

    protected void content() {
        System.out.println("啦啦啦,啦啦啦,我是卖报的小行家");
    }

    protected void end() {
        System.out.println("谢谢大家");
    }
}

public class JayChou extends Singer {
    /**
     * 唱歌的模版(或者说流程),父类已经为你准备好了.
     * 如果子类需要自己特有的内容,只需要根据模版,覆盖特定的步骤的方法即可
     */
    @Override
    protected void title() {
        System.out.println("夜曲");
    }

    @Override
    protected void content() {
        System.out.println("为你弹奏肖邦的夜曲,纪念我死去的爱情");
    }

    public static void main(String[] args) {
        JayChou jayChou = new JayChou();
        jayChou.sing(); // 这个sing就是模版方法
    }
}

Object类的几个重要方法

  1. equlas
  2. toString
  3. hashCode

需要注意的点

  1. 任何类都隐式的继承了Object
  2. 覆盖(重写)equlas方法时,总是应该覆盖hashCode方法
  3. 覆盖时,永远记得使用@Override注解来防止手残,编译器会检查你这个方法是不是和要覆盖的方法同名
updatedupdated2025-03-012025-03-01