基本介紹
- 原型模式(Prototype模式)是指:用原型實例指定創(chuàng)建對象的種類,并且通過拷 貝這些原型,創(chuàng)建新的對象 。
- 原型模式是一種創(chuàng)建型設(shè)計模式,允許一個對象再創(chuàng)建另外一個可定制的對象, 無需知道如何創(chuàng)建的細(xì)節(jié) 。
- 工作原理是:通過將一個原型對象傳給那個要發(fā)動創(chuàng)建的對象,這個要發(fā)動創(chuàng)建 的對象通過請求原型對象拷貝它們自己來實施創(chuàng)建,即 對象.clone()。
淺拷貝
復(fù)制一個對象,連帶屬性的值復(fù)制出來,屬性如果是引用類型,那么復(fù)制的是地址。
代碼實現(xiàn)(原型是重點(diǎn))
原型類
package com.yuan.dp.prototype.domain;
/**
* 實體類 綿羊
*
* @author Yuan-9826
*/
public class Sheep implements Cloneable {
private String name;
private String color;
private Friend friend;
public Sheep() {
}
public Sheep(String name, String color, Friend friend) {
this.name = name;
this.color = color;
this.friend = friend;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Friend getFirSheep() {
return friend;
}
public void setWeight(Friend friend) {
this.friend = friend;
}
@Override
public String toString() {
return "Sheep{" +
"name='" + name + '\'' +
", color='" + color + '\'' +
", friend='" + friend.hashCode() + '\'' +
'}';
}
/**
* 淺拷貝使用默認(rèn)方法 記得要強(qiáng)轉(zhuǎn)類型 不然調(diào)用的時候就要強(qiáng)轉(zhuǎn) 同理也要try catch
*
* @return
* @throws CloneNotSupportedException
*/
@Override
public Sheep clone() {
Sheep clone = null;
try {
clone = (Sheep) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
引用類型屬性類
package com.yuan.dp.prototype.domain;
import java.io.Serializable;
public class Friend implements Cloneable, Serializable {
public String name ;
public String hobby ;
/**
* 如果沒有引用類型 就用淺拷貝 默認(rèn)的
* @return
* @throws CloneNotSupportedException
*/
@Override
protected Friend clone() throws CloneNotSupportedException {
Friend friend = (Friend) super.clone();
return friend;
}
}
測試
package com.yuan.dp.prototype;
import com.yuan.dp.prototype.domain.Friend;
import com.yuan.dp.prototype.domain.Sheep;
/**
* 淺拷貝 只拷貝了屬性的值
*
* @author Yuan-9826
*/
public class Prototype_1 {
public static void main(String[] args) {
Friend friend = new Friend();
Sheep sheep_1 = new Sheep("喜羊羊", "白色", friend);
System.out.println("sheep_1 = " + sheep_1);
//sheep_1 = Sheep{name='喜羊羊', color='白色', friend='42121758'}
Sheep sheep_2 = sheep_1.clone();
System.out.println("sheep_2 = " + sheep_2);
//sheep_2 = Sheep{name='喜羊羊', color='白色', friend='42121758'}
System.out.println(sheep_1 == sheep_2);
//false
}
}