设计模式学习—06原型模式

原型模式

UML

原型模式

解释说明

  • 原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
  • 浅拷贝:若是引用类型的字段,复制其引用。
  • 深拷贝:若是引用类型的字段,创建新的对象再引用。
  • java中创建浅表副本可以通过实现 Cloneable 接口。

代码实现

  • 示例实现深拷贝。
  • InfoEntity.class
package learn06;

public class InfoEntity implements Cloneable {
    private String name;
    private int age;

    public InfoEntity(String name, int age) {
        this.name = name;
        this.age = 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;
    }

    //数据实体要实现Cloneable接口
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
  • Prototype.class
package learn06;

public abstract class Prototype {
    private int id;
    private InfoEntity info;

    public Prototype(int id, String name, int age) {
        this.id = id;
        this.info = new InfoEntity(name, age);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setInfo(InfoEntity info) {
        this.info = info;
    }

    public InfoEntity getInfo() {
        return info;
    }

    @Override
    public abstract Prototype clone();
}
  • ConcretePrototype.class
package learn06;

public class ConcretePrototype extends Prototype {

    public ConcretePrototype(int id, String name, int age) {
        super(id, name, age);
    }
    
    //私有构造方法,用于clone非基础类型数据
    private ConcretePrototype(InfoEntity info) {
        super(0, "", 0);
        InfoEntity infoEntity = null;
        try {
            infoEntity = (InfoEntity) info.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        this.setInfo(infoEntity);
    }

    public void display() {
        System.out.println("id:" + getId() + " name:" + getInfo().getName() + " age:" + getInfo().getAge());
    }

    @Override
    public Prototype clone() {
        ConcretePrototype concretePrototype = new ConcretePrototype(this.getInfo());
        concretePrototype.setId(this.getId());
        return concretePrototype;
    }
}
  • Main.class
import learn06.*;

public class Main {
    public static void main(String[] args) {
        ConcretePrototype a = new ConcretePrototype(1, "Jack", 20);

        ConcretePrototype b = (ConcretePrototype) a.clone();
        b.setId(2);
        b.getInfo().setName("Tim");
        b.getInfo().setAge(21);

        a.display();
        b.display();
    }
}

参考资料

  • 大话设计模式
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值