掘金 后端 ( ) • 2024-04-11 09:20

模板方法模式

模板方法模式,就是将一些具体层都会有重复的内容,都放在抽象层作为具体层的模板,让具体层的代码能更简洁,也更好地实现代码复用。

代码实现

若有一套试卷,有A和B两个学生来作答,其中的题目便就是A、B都不用自己去写的东西,即可以作为模板的东西。

空试卷:

/**
 * 模板方法模式
 */
public class Paper {
    public void question1(String answer){
        System.out.println("中国的国宝动物是啥?");
        System.out.println(answer);
    }

    public void question2(String answer){
        System.out.println("海绵宝宝的住所叫什么?");
        System.out.println(answer);
    }

    //答题卡
    public void answerCard(String answer1,String answer2){
        this.question1(answer1);
        this.question2(answer2);
    }
}

学生作答的试卷:

public class StudentAPaper extends Paper {
    public void finishPaper(){
        this.answerCard("熊猫","菠萝屋");
    }
}

public class StudentBPaper extends Paper {
    public void finishPaper(){
        this.answerCard("熊猫","狼堡");
    }
}

业务代码:

        StudentAPaper paperA = new StudentAPaper();
        StudentBPaper paperB = new StudentBPaper();
        paperA.finishPaper();
        System.out.println();
        paperB.finishPaper();

运行结果为:

中国的国宝动物是啥?
熊猫
海绵宝宝的住所叫什么?
菠萝屋

中国的国宝动物是啥?
熊猫
海绵宝宝的住所叫什么?
狼堡

像题目这种无需让两个学生抄题的可以复用的东西,便可以放在他们共同的父类中,此时题目就是提供给两个学生做题的模板。像这种将可以复用的代码放在抽象层,使得具体层在实现的时候能直接复用这个模板,就是使用了模板方法模式。

原型模式

让一个类实现cloneable接口并实现其clone方法,使得要复制此类的对象,只要调用其clone方法即可,这种使得对象的复制更方便的模式就是原型模式

代码实现

若学生的信息表有时要进行复制:

public class Information implements Cloneable{
    private String name;
    private String classes;
    private String id;

//省略一些不重要代码……

    public Information clone(){
        Information paper = null;
        try {
            paper = (Information) super.clone();
        } catch (CloneNotSupportedException e) {
            e.getMessage();
        }
        return paper;
    }
}

当要对其类的对象进行复制,也就是要对学生信息进行复制,直接调用其clone方法即可。

但是这种只是浅复制,如果学生信息中加了一个School类型的对象,就是学校信息,调用clone方法便只会复制其地址,即新的对象和原来的对象用的是同一个School对象的信息。

要进行深复制,即新复制的对象用的School对象是一个新的对象,则要保证被引用的数据的类型也实现了cloneable接口实现了clone方法。

School类:

public class School implements Cloneable{
    private String name;
    private String address;

    //省略一些不重要的代码……

    public School clone(){
        School school = null;
        try {
            school = (School) super.clone();

        } catch (CloneNotSupportedException e) {
            e.getMessage();
        }
        return school;
    }
}

新的Information类:

public class Information implements Cloneable{
    private String name;
    private String classes;
    private String id;
    private School school;

//省略一些不重要的代码……
    public Information clone(){
        Information paper = null;
        try {
            paper = (Information) super.clone();
            paper.school = this.school.clone();
        } catch (CloneNotSupportedException e) {
            e.getMessage();
        }
        return paper;
    }
}

如果要更深层次的深复制,比如School类中又有其他类型的引用类型的数据,以此类推,在clone方法中调用其对应的深层次的clone方法即可