原型模式

本文详细介绍了Java中克隆模式的实现方式,包括如何通过实现Cloneable接口并重写clone方法来复制对象,同时探讨了深拷贝和浅拷贝的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 定义:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
  2. 通用类图

            095700_DwPT_1169535.png

    3,实例代码

/**
 * 只是一个类,作为clone对象全局变量,clone对象被clone的时候,它会不会被clone
 */
public class TestObject {

    private String testName;


    public String getTestName() {
        return testName;
    }

    public void setTestName(String testName) {
        this.testName = testName;
    }
}

          

/**
 * 原型对象,用于clone测试
 */
public class ConcretePrototype implements Cloneable{

    private String attr1;

    private Integer attr2;

    private TestObject testObject;


    @Override
    protected Object clone() throws CloneNotSupportedException {
        ConcretePrototype concretePrototype = null;
        try {
            concretePrototype = (ConcretePrototype)super.clone();
        }catch (CloneNotSupportedException e){
            e.printStackTrace();
        }
        return concretePrototype;
    }


    public String getAttr1() {
        return attr1;
    }

    public void setAttr1(String attr1) {
        this.attr1 = attr1;
    }

    public Integer getAttr2() {
        return attr2;
    }

    public void setAttr2(Integer attr2) {
        this.attr2 = attr2;
    }

    public TestObject getTestObject() {
        return testObject;
    }

    public void setTestObject(TestObject testObject) {
        this.testObject = testObject;
    }
}

 

/**
 * 显示clone 结果
 */
public class MineClient {
    public static void main(String[] args) {
        TestObject testObject = new TestObject();
        testObject.setTestName("testName");

        ConcretePrototype concretePrototype = new ConcretePrototype();
        concretePrototype.setAttr1("ceshi");
        concretePrototype.setAttr2(1);
        concretePrototype.setTestObject(testObject);
        try {
            ConcretePrototype cp = (ConcretePrototype)concretePrototype.clone();
            System.out.println(cp.getAttr1());
            System.out.println(cp.getAttr2());
            System.out.println(cp.getTestObject().getTestName());
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

4,注意事项:

  • 利用clone 创造对象的时候,不会执行对象的构造方法
  • 要注意深拷贝和浅拷贝(在对象拷贝的时候,对象关联的数组和引用对象是不会被拷贝的,其他基本类型包括string可以被拷贝)

转载于:https://my.oschina.net/u/1169535/blog/828760

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值