JAVA设计模式之【原型模式】

简介:

1.案例一
学生复制

package Prototype;

/**
 * Created by Jim on 2016/10/1.
 */
public class Student implements Cloneable{
    private String stuName;
    private String stuSex;
    private int stuAge;
    private String stuMajor;
    private String stuCollege;
    private String stuUniversity;

    public Student(String stuName,String stuSex,int stuAge,String stuMajor,String stuCollege,String stuUniversity) { // 构造函数
        this.stuName = stuName;
        this.stuSex = stuSex;
        this.stuAge = stuAge;
        this.stuMajor = stuMajor;
        this.stuCollege = stuCollege;
        this.stuUniversity = stuUniversity;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public void setStuSex(String stuSex) {
        this.stuSex = stuSex;
    }

    public void setStuAge(int stuAge) {
        this.stuAge = stuAge;
    }

    public void setStuMajor(String stuMajor) {
        this.stuMajor = stuMajor;
    }

    public void setStuCollege(String stuCollege) {
        this.stuCollege = stuCollege;
    }

    public void setStuUniversity(String stuUniversity) {
        this.stuUniversity = stuUniversity;
    }

    public String getStuName() {
        return this.stuName;
    }

    public String getStuSex() {
        return this.stuSex;
    }

    public int getStuAge() {
        return this.stuAge;
    }

    public String getStuMajor() {
        return this.stuMajor;
    }

    public String getStuCollege() {
        return this.stuCollege;
    }

    public String getStuUniversity() {
        return this.stuUniversity;
    }

    public Student clone() { // 实现克隆
        Student cpStudent = null;
        try{
            cpStudent=(Student)super.clone();
        }catch (CloneNotSupportedException e) {

        }
        return cpStudent;
    }
}

// 继续写类
class MainClass
{
    public static void main(String args[]) {
        Student stu1,stu2,stu3;
        stu1 = new Student("张无忌","男",24,"软件","信息工程学院","南京财经大学");

        // 使用原型
        stu2 = stu1.clone();
        stu2.setStuName("杨过");

        stu3 = stu1.clone();
        stu3.setStuName("小龙女");
        stu3.setStuSex("女");

        System.out.print("姓名:" + stu1.getStuName());
        System.out.print(",性别:" + stu1.getStuSex());
        System.out.print(",年龄:" + stu1.getStuAge());
        System.out.print(",专业:" + stu1.getStuMajor());
        System.out.print(",学院:" + stu1.getStuCollege());
        System.out.print(",大学:" + stu1.getStuUniversity());
        System.out.println();


        System.out.print("姓名:" + stu2.getStuName());
        System.out.print(",性别:" + stu2.getStuSex());
        System.out.print(",年龄:" + stu2.getStuAge());
        System.out.print(",专业:" + stu2.getStuMajor());
        System.out.print(",学院:" + stu2.getStuCollege());
        System.out.print(",大学:" + stu2.getStuUniversity());
        System.out.println();

        System.out.print("姓名:" + stu3.getStuName());
        System.out.print(",性别:" + stu3.getStuSex());
        System.out.print(",年龄:" + stu3.getStuAge());
        System.out.print(",专业:" + stu3.getStuMajor());
        System.out.print(",学院:" + stu3.getStuCollege());
        System.out.print(",大学:" + stu3.getStuUniversity());
        System.out.println();
    }
}

执行结果:
姓名:张无忌,性别:男,年龄:24,专业:软件,学院:信息工程学院,大学:南京财经大学
姓名:杨过,性别:男,年龄:24,专业:软件,学院:信息工程学院,大学:南京财经大学
姓名:小龙女,性别:女,年龄:24,专业:软件,学院:信息工程学院,大学:南京财经大学

2.邮件与附件
附件类

package Prototype;

/**
 * Created by Jim on 2016/10/1.
 */
public class Attachment {
    public void download() {
        System.out.println("下载附件");
    }
}

邮件类

package Prototype;

/**
 * Created by e550 on 2016/10/1.
 */
public class Email implements Cloneable{
    private Attachment attachment = null;

    public Email() {
        this.attachment = new Attachment();
    }

    public Object clone() {
        Email clone = null;
        try{
            clone=(Email)super.clone();
        }catch (CloneNotSupportedException e){
            System.out.println("Clone failure!");
        }
        return clone;
    }

    public Attachment getAttachment() {
        return this.attachment;
    }

    public void display() {
        System.out.println("查看邮件");
    }
}

客户端

package Prototype;

/**
 * Created by e550 on 2016/10/1.
 */
public class Client {
    public static void main(String a[]) {
        Email email,cpEmail;
        email = new Email();
        cpEmail = (Email)email.clone();

        System.out.println("email==cpEmail?");
        System.out.println(email==cpEmail);

        System.out.println("email.getAttachment==cpEmail.getAttachment?");
        System.out.println(email.getAttachment()==cpEmail.getAttachment());
    }
}

执行结果

email==cpEmail?
false
email.getAttachment==cpEmail.getAttachment?
true

说明:
这种克隆,没有把引用的变量克隆出来。

3.改造邮件类,通过流实现深克隆
附件类

package Prototype.deepClone;
import java.io.*;

/**
 * Created by e550 on 2016/10/1.
 */
public class Attachment implements Serializable{
    public void download() {
        System.out.println("下载附件");
    }
}

邮件类

package Prototype.deepClone;
import java.io.*;
/**
 * Created by e550 on 2016/10/1.
 */
public class Email implements Serializable{
    private Attachment attachment = null;
    public Email() {
        this.attachment = new Attachment();
    }

    public Object deepClone() throws IOException , ClassNotFoundException, OptionalDataException
    {
        // 将对象写入流中
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        ObjectOutputStream oss = new ObjectOutputStream(bao);
        oss.writeObject(this);

        //将对象从流中取出
        ByteArrayInputStream bis = new ByteArrayInputStream(bao.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return(ois.readObject());
    }

    public Attachment getAttachment() {
        return this.attachment;
    }

    public void display() {
        System.out.println("查看邮件");
    }

}

客户端类

package Prototype.deepClone;

public class Client
{
    public static void main(String a[])
    {
        Email email,copyEmail=null;

        email=new Email();

        try{
            copyEmail=(Email)email.deepClone();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }


        System.out.println("email==copyEmail?");
        System.out.println(email==copyEmail);

        System.out.println("email.getAttachment==copyEmail.getAttachment?");
        System.out.println(email.getAttachment()==copyEmail.getAttachment());
    }
}

执行结果

email==copyEmail?
false
email.getAttachment==copyEmail.getAttachment?
false

点评
通过流实现了深克隆,把对象中的值类型和引用类型都克隆了。
这种方式比较复杂一点,可以根据实际情况来选择使用。



本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/5925430.html,如需转载请自行联系原作者

相关文章
|
IDE Go 开发工具
Go开发IDE全览:GoLand vs VSCode全面解析
Go开发IDE全览:GoLand vs VSCode全面解析
860 0
Go语言中的数组、切片和映射解析
Go语言中的数组、切片和映射解析
|
安全 iOS开发
iOS页面布局:UIScrollView的布局问题
iOS页面布局:UIScrollView的布局问题
461 63
|
10月前
|
Prometheus 监控 Cloud Native
无痛入门Prometheus:一个强大的开源监控和告警系统,如何快速安装和使用?
Prometheus 是一个完全开源的系统监控和告警工具包,受 Google 内部 BorgMon 系统启发,自2012年由前 Google 工程师在 SoundCloud 开发以来,已被众多公司采用。它拥有活跃的开发者和用户社区,现为独立开源项目,并于2016年加入云原生计算基金会(CNCF)。Prometheus 的主要特点包括多维数据模型、灵活的查询语言 PromQL、不依赖分布式存储、通过 HTTP 拉取时间序列数据等。其架构简单且功能强大,支持多种图形和仪表盘展示模式。安装和使用 Prometheus 非常简便,可以通过 Docker 快速部署,并与 Grafana 等可
4401 2
|
数据可视化 数据处理
Tableau可视化设计案例-02Tableau数据处理、折线图
Tableau可视化设计案例-02Tableau数据处理、折线图
Tableau可视化设计案例-02Tableau数据处理、折线图
|
人工智能 Cloud Native 大数据
100+PDF开放下载!云栖大会一手资料来啦!(持续更新中)
我们为大家整理了本次云栖大会主分论坛共100多个PDF,欢迎下载学习!
25974 73
|
SQL 关系型数据库 MySQL
sql数据库命令
SQL(Structured Query Language,结构化查询语言)是用于管理关系数据库的标准编程语言。以下是一些常用的 SQL 数据库命令: 1. **创建数据库**: ``
111 7
|
运维 Cloud Native 持续交付
构建未来:云原生架构在企业转型中的关键角色
【5月更文挑战第21天】 随着数字化转型的浪潮席卷全球,企业正面临前所未有的挑战与机遇。本文深入探讨了云原生架构如何成为推动企业敏捷性、可扩展性和创新能力的核心动力。通过分析云原生技术的基本原理及其在各行各业中的应用案例,揭示了该技术如何助力企业实现资源优化、加快产品上市时间以及提高服务质量。文章旨在为企业决策者和技术实践者提供洞见,以便更好地理解和应用云原生架构,从而在竞争激烈的市场中保持领先地位。
|
存储 弹性计算 云计算
HCIE-Cloud Computing Day01:云计算简介
HCIE-Cloud Computing Day01:云计算简介
1091 0