原型模式
介绍:
在软件系统中,有时候需要多次创建某一类型的对象,为了简化创建过程,可以只创建一个对象,然后再通过克隆的方式复制出多个相同的对象,这就是原型模式的设计思想。
定义:
原型模式是一种对象型模式,可指定创建对象的种类,并通过复制这些原型创建新的对象。
结构:
1、Prototype(抽象原型类)
2、ConcretePrototype(具体原型类)
3、Client(客户类)
模式实例之浅克隆
浅克隆:在浅克隆中,被复制对象的所有普通成员变量都具有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象。换言之,浅克隆仅仅复制所考虑的对象,而不复制它所引用的成员对象,也就是其中的成员对象并不复制。
public class Customer implements Cloneable {
private String id;//客户编号
private String name;//客户姓名
private Address address;//客户地址,成员对象
public Customer(String id,String name,Address address){
this.id = id;
this.name = name;
this.address = address;
}
//克隆方法
public Customer clone(){
Customer customer = null;
try{
customer = (Customer)super.clone();
}catch(CloneNotSupportedException e){
e.getMessage();
}
return customer;
}
//打印
public void print(){
System.out.println("客户编号:"+getId()+" 客户姓名:"+getName());
getAddress().printAddress();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
public class Address {
private String home;//家庭住址
private String tel;//电话
private String email;//邮箱
public Address(String home,String tel,String email){
this.home = home;
this.tel = tel;
this.email = email;
}
//打印地址方法
public void printAddress(){
System.out.println("地址:");
System.out.println("家庭住址:"+getHome());
System.out.println("电话:"+getTel());
System.out.println("邮箱:"+getEmail());
}
public String getHome() {
return home;
}
public void setHome(String home) {
this.home = home;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
//测试
public class Test {
public static void main(String[] args){
Address address = new Address("广东", "10086", "[email protected]");
Customer cus = new Customer("1001","王五",address);
//浅克隆
Customer cusClone = cus.clone();
cusClone.setName("克隆的王五");
cusClone.setId("1002");
System.out.println("分别打印:");
cus.print();
cusClone.print();
System.out.println("浅克隆的两个对象是否相等:"+cus.equals(cusClone));
System.out.println("浅克隆的属性对象是否相等:"+cus.getAddress().equals(cusClone.getAddress()));
}
}
第一个判断是false,说明内存中存在两个不同的对象,即通过复制得到的对象与原型对象的引用不一致。
第二个判断为true,说明对象虽然复制了一份,但两个对象共同引用一个成员对象,即复制对象仍然引用原型对象的成员对象,没有再复制另一个。