設計模式之原型模式

來源:互聯網
上載者:User

什麼是原型設計模式?

原型模式其實就是一個對象再建立另一個與原對象相同內容對象,而讓建立過程不知道任何細節的方法.

為什麼要使用原型設計模式?

在物件導向編程過程中常常會碰見需要複製對象的情況,所以這是我們就會使用原型模式,原型模式又叫複製方法.

怎麼使用原型設計模式?

原型模式原理其實很簡單,例如我們有個Student.class要對它進行複製,那麼定義一個MyCloneAble的介面,介面中提供一個Clone()的方法,Student.class實現該介面,並在Clone()方法中返回被複製的對象(複製的對象即new出來把當前對象的值付給它即可.)基本UML

代碼具體實現:

MyCloneAble.interface

public interface MyCloneable {public Object myClone();}

Student.class

public class Student implements MyCloneable{private String name;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic Object myClone() {// TODO Auto-generated method stubStudent student = new Student();student.setAge(this.age);student.setName(this.name);return student;}}

Main.class

public class Main {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubStudent s1 = new Student();s1.setAge(20);s1.setName("huangli");Student s2 = (Student)s1.myClone();System.out.println("name "+s2.getName()+" age "+s2.getAge());}}

輸出為

name huangli age 20 

java中的clone,在java中我們如果需要去clone一個對象就不需要去自己定義MyCloneAble介面了,因為Clone這個功能實在是太常用了,java的sdk早就為我們封裝好了方法,而且使用起來也是很簡單的.

java的sdk為我們提供了Cloneable介面,具體介紹如下

然後Object有一個clone()方法

具體實現複製的做法要求是:

1,必須實現Cloneable介面(這個介面沒有方法,只起到mark作用)

2,重寫Object中clone()方法並將該方法許可權改為public,其中裡面的super()方法必須執行!該方法返回的對象即為clone對象。

淺複製和深複製

所謂的淺度複製就是在複製過程中只複製了基礎資料型別 (Elementary Data Type),對於類對象只複製了該對象的引用而沒有複製對象本身。

深複製呢,就是它不光複製基礎資料型別 (Elementary Data Type),對於類對象也一起複製.如果想要實現深複製,只需要對需要複製的類內部類對象實行淺複製即可.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.