这篇文章来看看原型模式!!
概念:用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
创建对象,拷贝对象。。。。晦涩难懂,直接上栗子!!!!
创建一个Student类,各种set,get方法,最关键的是CLone方法,也就是拷贝Student类创建一个新对象student1
package com.example.mytry; /** * 原型模式Student类 */ public class Student implements Cloneable { private String name; private int age; private int count; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } @Override protected Object clone() throws CloneNotSupportedException { Student student = null; try { student = (Student) super.clone(); student.name = this.name; student.age = this.age; student.count = this.count; } catch (Exception e) { e.printStackTrace(); } return student; } }
package com.example.mytry; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; /** * 原型模式案例 */ public class MainActivity extends AppCompatActivity { private Student student1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Student student = new Student(); student.setName("张三"); student.setAge(90); student.setCount(100); try { student1 = (Student) student.clone(); student1.setName("历史"); } catch (CloneNotSupportedException e) { e.printStackTrace(); } Toast.makeText(this, student1.toString(), Toast.LENGTH_SHORT).show(); } @Override public String toString() { return "姓名:" + student1.getName() + "年龄:" + student1.getAge() + "分数" + student1.getCount(); }}