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

简介:

422101-20161001080404360-1750947788.png

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,如需转载请自行联系原作者

相关文章
|
6天前
|
NoSQL Cloud Native Redis
Redis核心开发者的新征程:阿里云与Valkey社区的技术融合与创新
阿里云瑶池数据库团队后续将持续参与Valkey社区,如过往在Redis社区一样耕耘,为开源社区作出持续贡献。
Redis核心开发者的新征程:阿里云与Valkey社区的技术融合与创新
|
5天前
|
关系型数据库 分布式数据库 数据库
PolarDB闪电助攻,《香肠派对》百亿好友关系实现毫秒级查询
PolarDB分布式版助力《香肠派对》实现百亿好友关系20万QPS的毫秒级查询。
PolarDB闪电助攻,《香肠派对》百亿好友关系实现毫秒级查询
|
7天前
|
消息中间件 Cloud Native Serverless
RocketMQ 事件驱动:云时代的事件驱动有啥不同?
本文深入探讨了云时代 EDA 的新内涵及它在云时代再次流行的主要驱动力,包括技术驱动力和商业驱动力,随后重点介绍了 RocketMQ 5.0 推出的子产品 EventBridge,并通过几个云时代事件驱动的典型案例,进一步叙述了云时代事件驱动的常见场景和最佳实践。
115028 1
|
8天前
|
弹性计算 安全 API
访问控制(RAM)|云上安全使用AccessKey的最佳实践
集中管控AK/SK的生命周期,可以极大降低AK/SK管理和使用成本,同时通过加密和轮转的方式,保证AK/SK的安全使用,本次分享为您介绍产品原理,以及具体的使用步骤。
101800 1
|
7天前
|
自然语言处理 Cloud Native Serverless
通义灵码牵手阿里云函数计算 FC ,打造智能编码新体验
近日,通义灵码正式进驻函数计算 FC WebIDE,让使用函数计算产品的开发者在其熟悉的云端集成开发环境中,无需再次登录即可使用通义灵码的智能编程能力,实现开发效率与代码质量的双重提升。
95382 2
Doodle Jump — 使用Flutter&Flame开发游戏真不错!
用Flutter&Flame开发游戏是一种什么体验?最近网上冲浪的时候,我偶然发现了一个国外的游戏网站,类似于国内的4399。在浏览时,我遇到了一款经典的小游戏:Doodle Jump...
112727 12
|
12天前
|
SQL 存储 JSON
Flink+Paimon+Hologres 构建实时湖仓数据分析
本文整理自阿里云高级专家喻良,在 Flink Forward Asia 2023 主会场的分享。
71310 1
Flink+Paimon+Hologres 构建实时湖仓数据分析
|
15天前
|
弹性计算 运维 安全
访问控制(RAM)|云上程序使用临时凭证的最佳实践
STS临时访问凭证是阿里云提供的一种临时访问权限管理服务,通过STS获取可以自定义时效和访问权限的临时身份凭证,减少长期访问密钥(AccessKey)泄露的风险。本文将为您介绍产品原理,以及具体的使用步骤。
151041 4
|
14天前
|
监控 负载均衡 Java
深入探究Java微服务架构:Spring Cloud概论
**摘要:** 本文深入探讨了Java微服务架构中的Spring Cloud,解释了微服务架构如何解决传统单体架构的局限性,如松耦合、独立部署、可伸缩性和容错性。Spring Cloud作为一个基于Spring Boot的开源框架,提供了服务注册与发现、负载均衡、断路器、配置中心、API网关等组件,简化了微服务的开发、部署和管理。文章详细介绍了Spring Cloud的核心模块,如Eureka、Ribbon、Hystrix、Config、Zuul和Sleuth,并通过一个电商微服务系统的实战案例展示了如何使用Spring Cloud构建微服务应用。
103517 9
|
14天前
|
Java 数据处理 调度
更高效准确的数据库内部任务调度实践,阿里云数据库SelectDB 内核 Apache Doris 内置 Job Scheduler 的实现与应用
Apache Doris 2.1 引入了内置的 Job Scheduler,旨在解决依赖外部调度系统的问题,提供秒级精确的定时任务管理。