1. 程式人生 > >設計模式快速學習(五)原型模式

設計模式快速學習(五)原型模式

用於建立重複的物件,同時又能保證效能。通俗的講,原型模式就是克隆物件,直接copy位元組碼,不走構造方法,效能非常高。ORM中經常用到。

注意

只支援9種資料型別的深拷貝: 8大基本型別(int long float double boolean char short byte )+String 其他(List等)資料型別預設都是淺拷貝,但是我們也能通過他們自身的clone方法來深拷貝。

        List list = new ArrayList();
        List cloneList = (List) ((ArrayList) list).clone();
複製程式碼
Prototype.java

實現Cloneable介面,並且重寫clone()方法。

public class Prototype implements Cloneable{
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
複製程式碼

:如果不實現該介面而直接呼叫clone()方法會丟擲CloneNotSupportedException異常

PeoplePrototype.java

人原型,用來做被拷貝的物件。

public class PeoplePrototype extends Prototype{
    private int age;
    private String name;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void set
Age(int age) { this.age = age; } } 複製程式碼
Main.java
public class Main {
    public static void main(String[] args) {
        PeoplePrototype prototype = new PeoplePrototype();
        prototype.setAge(20);
        prototype.setName("FantJ");
        try {
            PeoplePrototype clone = (PeoplePrototype)prototype.clone();
            System.out.println(clone.getAge());
            System.out.println(clone == prototype);
            System.out.println(clone+"    "+prototype);
            System.out.println(clone.getClass()  +"     "+ prototype.getClass());
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
複製程式碼

控制檯列印:

20
false
[email protected]    [email protected]
class com.fantj.prototype.ConcretePrototype     class com.fantj.prototype.ConcretePrototype
複製程式碼