原型模式
也称为克隆模式,属于创建型模式
普通版
package com.demo.prototype;
/**
* 原型模式(克隆模式)
* 创建型模式
* 就是通过原型对象返回一个完全相同或相近的对象,包括其中的属性值
* 可以在不知道对象的具体类型的情况下创造对象
* 并且对于那些创建十分耗时的对象来说,clone比new速度快
*/
public class Prototype implements Cloneable{
//JDK中有实现原型模式的方法,但是该对象所对应的类必须实现Cloneable的接口
Prototype prototype = new Prototype();
public Prototype Clone() throws CloneNotSupportedException {
return (Prototype) prototype.clone();
}
}
深克隆原理版
package com.demo.prototype;
/**
* 深克隆原理版
* 由下可看出:
* 无论是对克隆对象d1的Y或者通过d1修改C的X的值
* 都不再对原型对象的值进行修改,也就是互不影响了
* 原理:
* 深克隆在对原型对象进行克隆时,会将原型对象的每个引用类型的属性也克隆一份
* 并且赋值给克隆对象
*/
public class DeepPrototype {
public static void main(String[] args) throws CloneNotSupportedException {
C c = new C();
c.setX(1);
D d = new D();
d.setY(2);
d.setC(c);
D d1 = (D)d.clone();
d1.setY(3);
System.out.println(d.getY()+"----"+d.getC().getX());//2--1
System.out.println(d1.getY()+"----"+d1.getC().getX());//3--1
d1.getC().setX(4);
System.out.println(d.getY()+"----"+d.getC().getX());//2--1
System.out.println(d1.getY()+"----"+d1.getC().getX());//3--4
}
}
class C implements Cloneable {
private int x;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
}
//实现Cloneable接口
class D implements Cloneable {
private int y;
private C c;
@Override
public Object clone() throws CloneNotSupportedException {
/**
* 1.调用clone方法获取克隆对象
* 2.获取c对象
* 3.将c对象的克隆对象存入d克隆对象中
*/
D d = (D) super.clone();
C c = d.getC();
d.setC((C) c.clone());
return d;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
}
深克隆进阶版
package com.demo.prototype;
import java.io.*;
/**
* 深克隆进阶版
* 序列化反序列化实现深克隆
*
*
*/
public class DeepPrototypeer {
public static void main(String[] args) throws IOException, ClassNotFoundException {
E e= new E();
e.setA(1);
F f =new F();
f.setB(2);
f.setE(e);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(bos);
os.writeObject(f);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
F f1 =(F)ois.readObject();
f1.setB(3);
f1.getE().setA(4);
System.out.println(f.getB()+"--"+f.getE().getA());//2--1
System.out.println(f1.getB()+"--"+f1.getE().getA());//3--4
}
}
class E implements Serializable {
private int a;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
class F implements Serializable{
private int b;
private E e;
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public E getE() {
return e;
}
public void setE(E e) {
this.e = e;
}
}