zoukankan      html  css  js  c++  java
  • prototype原型模式

    /**
    * 原型模式 Prototype
    * 用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象
    */

    需求:
    public class Resume {
    /**
    * 要求:一个简历类,必须有姓名,可以设置性别和年龄,可以设置工作经历,最终需要三份简历
    */
    String name;
    int age;
    String gender;
    String timeArea;
    String company;

    public Resume(String name) {
    this.name = name;
    }

    public void setPersonInfo(String gender, int age){
    this.gender = gender;
    this.age = age;
    }

    public void setWorkExperience(String timeArea, String company){
    this.timeArea = timeArea;
    this.company = company;
    }

    public void display(){
    System.out.println(name + gender + age);
    System.out.println("工作经历: " + timeArea +" " + company);
    }

    public static void main1(String[] args){
    Resume a = new Resume("大鸟");
    a.setPersonInfo("男", 21);
    a.setWorkExperience("上海", "xxx公司");

    Resume b = new Resume("大鸟");
    b.setPersonInfo("男", 21);
    b.setWorkExperience("上海", "xxx公司");

    Resume c = new Resume("大鸟");
    c.setPersonInfo("男", 21);
    c.setWorkExperience("上海", "xxx公司");

    a.display();
    b.display();
    c.display();

    }

    改进:
      
    public void copySome(String[] args){
    Resume a = new Resume("大鸟");
    a.setPersonInfo("男", 21);
    a.setWorkExperience("上海", "xxx公司");
    Resume b = a;
    Resume c = a;

    a.display();
    b.display();
    c.display();
    }

    引出原型模式。

    深拷贝与浅拷贝:

    区别在于浅拷贝对于引用数据类型只是引用的传递,可能导致克隆体和本体共用一个引用变量,造成互相影响。深拷贝需要重写clone,进行引用对象的值传递。

    
    
  • 相关阅读:
    C++ CGI Helloword
    国内外12个免费域名解析服务网站推荐
    U制作LFS linux
    LFS 中文版手册发布:如何打造自己的 Linux 发行版
    windows下的BT服务器搭建方案
    Linux下搭建BT服务器
    Codeforces 842B Gleb And Pizza【几何,水】
    Codeforces 842A Kirill And The Game【暴力,水】
    Wannafly模拟赛 A.矩阵(二分答案+hash)
    数据结构学习笔记【持续更新】
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/6865939.html
Copyright © 2011-2022 走看看