原型(Prototype)模式——Java设计模式(五)

原型模式简介

原型模式(Prototype Pattern):是用于创建重复的对象,同时又能保证性能。
分类:创建型模式。

这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。
例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。

意图:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
主要解决:在运行期建立和删除原型。

角色结构

抽象原型类(Prototype):声明克隆自身的接口。
具体原型类(ConcretePrototype):实现克隆的具体操作。
客户类(Client):让一个原型克隆自身,从而获得一个新的对象。

具体实现

通过已有简历复印(克隆)一份新的简历。

步骤一:给出实现了抽象原型类的具体原型类。
/**
 * CurriculumVitae(简历),具体原型类——实现了克隆的具体操作的类。
 * Cloneable——接口,抽象原型类。
 * @author Administrator
 *
 */
public class CurriculumVitae implements Cloneable {
    private String name;
    private String personalInfo;
    private String ability;
    private String other;

    public CurriculumVitae(String name, String info, String ability, String other) {
        this.name = name;
        this.personalInfo = info;
        this.ability = ability;
        this.other = other;
    }

    public String getName() {
        return name;
    }

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

    public String getPersonalInfo() {
        return personalInfo;
    }

    public void setPersonalInfo(String personalInfo) {
        this.personalInfo = personalInfo;
    }

    public String getAbility() {
        return ability;
    }

    public void setAbility(String ability) {
        this.ability = ability;
    }

    public String getOther() {
        return other;
    }

    public void setOther(String other) {
        this.other = other;
    }

    @Override
    public Object clone() {
        CurriculumVitae cv = null;
        try {
            cv = (CurriculumVitae) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        return cv;
    }

    @Override
    public String toString() {
        return this.name + ":" + this.personalInfo + " [" + this.ability + "]" + " " + this.other;
    }

    public void show() {
        System.out.println(this);
    }
}
步骤二:给出Client类。即,测试类。
public class Client {
    public static void main(String[] args) {
        System.out.println("原本");
        CurriculumVitae cv = new CurriculumVitae("张三", "男-20-182********", "精通Java", "喜欢编程");
        cv.show();

        System.out.println("副本");
        CurriculumVitae cvCopy = (CurriculumVitae) cv.clone();
        cvCopy.show();
    }
}
步骤三:验证结果。
原本
张三:男-20-182******** [精通Java] 喜欢编程
副本
张三:男-20-182******** [精通Java] 喜欢编程

总结

何时使用:

  1. 当一个系统应该独立于它的产品创建,构成和表示时。
  2. 当要实例化的类是在运行时刻指定时,例如,通过动态装载。
  3. 为了避免创建一个与产品类层次平行的工厂类层次时。
  4. 当一个类的实例只能有几个不同状态组合中的一种时,建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。

如何解决:利用已有的一个原型对象,快速地生成和原型对象一样的实例。
关键代码:

  1. 实现克隆操作,在 JAVA 继承 Cloneable,重写 clone(),在 .NET 中可以使用 Object 类的 MemberwiseClone() 方法来实现对象的浅拷贝或通过序列化的方式来实现深拷贝。
  2. 原型模式同样用于隔离类对象的使用者和具体类型(易变类)之间的耦合关系,它同样要求这些”易变类”拥有稳定的接口。

应用实例: 1、细胞分裂。 2、JAVA 中的 Object clone() 方法。

优点:

  1. 性能提高。
  2. 逃避构造函数的约束。

缺点:

  1. 配备克隆方法需要对类的功能进行通盘考虑,这对于全新的类不是很难,但对于已有的类不一定很容易,特别当一个类引用不支持串行化的间接对象,或者引用含有循环结构的时候。
  2. 必须实现 Cloneable 接口。

使用场景:

  1. 资源优化场景。
  2. 类初始化需要消化非常多的资源,这个资源包括数据、硬件资源等。
  3. 性能和安全要求的场景。
  4. 通过 new 产生一个对象需要非常繁琐的数据准备或访问权限,则可以使用原型模式。
  5. 一个对象多个修改者的场景。
  6. 一个对象需要提供给其他对象访问,而且各个调用者可能都需要修改其值时,可以考虑使用原型模式拷贝多个对象供调用者使用。
  7. 在实际项目中,原型模式很少单独出现,一般是和工厂方法模式一起出现,通过 clone 的方法创建一个对象,然后由工厂方法提供给调用者。原型模式已经与 Java 融为浑然一体,大家可以随手拿来使用。

注意事项:与通过对一个类进行实例化来构造新对象不同的是,原型模式是通过拷贝一个现有对象生成新对象的。
浅拷贝:实现 Cloneable,重写;
深拷贝:通过实现 Serializable 读取二进制流。

补充(深克隆和浅克隆)

关于深克隆和浅克隆。
简单来说:

  1. 浅克隆:不会克隆原对象中的引用类型,仅仅拷贝了引用类型的指向;
  2. 深克隆:拷贝所有。

用代码来举例说明,对上面例子加上引用类型:

//浅克隆例子:
/**
 * CurriculumVitae(简历),具体原型类——实现了克隆的具体操作的类。
 * Cloneable——接口,抽象原型类。
 * @author Administrator
 *
 */
public class CurriculumVitae implements Cloneable {
    private String name;
    private String personalInfo;
    private String ability;
    private String other;
    private Birthday birthday;

    public CurriculumVitae(String name, String info, String ability, String other, Birthday birthday) {
        this.name = name;
        this.personalInfo = info;
        this.ability = ability;
        this.other = other;
        this.birthday = birthday;
    }

    public Birthday getBirthday() {
        return birthday;
    }

    public void setBirthday(Birthday birthday) {
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

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

    public String getPersonalInfo() {
        return personalInfo;
    }

    public void setPersonalInfo(String personalInfo) {
        this.personalInfo = personalInfo;
    }

    public String getAbility() {
        return ability;
    }

    public void setAbility(String ability) {
        this.ability = ability;
    }

    public String getOther() {
        return other;
    }

    public void setOther(String other) {
        this.other = other;
    }

    @Override
    public Object clone() {
        CurriculumVitae cv = null;
        try {
            cv = (CurriculumVitae) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        return cv;
    }

    @Override
    public String toString() {
        return this.name + "(" + this.birthday + "):" + this.personalInfo 
                + " [" + this.ability + "]" + " " + this.other;
    }

    public void show() {
        System.out.println(this);
    }
}

/**
 * Birthday类
 * @author Administrator
 *
 */
public class Birthday {
    private String year;
    private String month;
    private String day;

    public Birthday(String year, String month, String day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getMonth() {
        return month;
    }

    public void setMonth(String month) {
        this.month = month;
    }

    public String getDay() {
        return day;
    }

    public void setDay(String day) {
        this.day = day;
    }

    @Override
    public String toString() {
        return this.year + "-" + this.month + "-" + this.day;
    }
}

/**
 * 测试类
 * @author Administrator
 *
 */
public class Client {
    public static void main(String[] args) {
        System.out.print("原本:");
        CurriculumVitae cv = new CurriculumVitae("张三", "男-20-182********", "精通Java", "喜欢编程", 
                new Birthday("1996", "01", "01"));
        cv.show();

        System.out.print("副本:");
        CurriculumVitae cvCopy = (CurriculumVitae) cv.clone();
        cvCopy.getBirthday().setYear("2000");
        cvCopy.show();

        System.out.print("原本:");
        cv.show();
    }
}

//运行结果
原本:张三(1996-01-01):男-20-182******** [精通Java] 喜欢编程
副本:张三(2000-01-01):男-20-182******** [精通Java] 喜欢编程
原本:张三(2000-01-01):男-20-182******** [精通Java] 喜欢编程

可以看到在修改了克隆出的副本后,修改副本之后,原本变了,说明克隆的时候只克隆了birthday的引用,并没有克隆它,导致修改副本会影响原本,这是浅克隆。
原型模式是深克隆。
如何实现深克隆?

  1. 让引用类型的类中也实现clone,即,克隆的时候递归克隆;
  2. 实现序列化,将对象写入到流中,这样对象的内容就变成了字节流,也就不存在什么引用了。然后读取字节流反序列化为对象就完成了完全的复制操作了。
//深克隆例子
//只把对上面例子改动的地方粘贴出来
    /**
     * 这是CurriculumVitae类
     * 对引用类型也做一个克隆
     */
    @Override
    public Object clone() {
        CurriculumVitae cv = null;
        try {
            cv = (CurriculumVitae) super.clone();
            cv.birthday = (Birthday) birthday.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        return cv;
    }

    /*
     * 这是Birthday类。需要该类实现Cloneable接口,即public class Birthday implements Cloneable 
     * 然后该类重写clone方法。
     */
    @Override
    public Object clone() {
        Birthday birthday = null;
        try {
            birthday = (Birthday) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        return birthday;
    }

//运行结果
原本:张三(1996-01-01):男-20-182******** [精通Java] 喜欢编程
副本:张三(2000-01-01):男-20-182******** [精通Java] 喜欢编程
原本:张三(1996-01-01):男-20-182******** [精通Java] 喜欢编程

可以看到,副本的修改不会影响到原本,达到了目的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值