当前位置:网站首页>Gof23 - prototype mode

Gof23 - prototype mode

2022-06-26 06:15:00 Kuxiaoya

Archetypal model :

Archetypal model (Prototype Pattern) Is used to create duplicate objects , At the same time, it can guarantee the performance . This type of design pattern is a creation pattern , It provides the best way to create objects .
This pattern is to implement a prototype interface , This interface is used to create a clone of the current object . When the cost of creating objects directly is high , Then use this mode

 Insert picture description here

The code is as follows :

package prototype.Demo1;

import java.util.Date;

/** * 1、 Implement an interface  Cloneable * 2、 Rewrite a method  * */

public class Video  implements Cloneable {
    
    private String name;
    private Date createTime;

    @Override
    protected Object clone() throws CloneNotSupportedException {
    
        return super.clone();
    }

    public Video() {
    
    }

    public Video(String name, Date createTime) {
    
        this.name = name;
        this.createTime = createTime;
    }

    public String getName() {
    
        return name;
    }

    public void setName(String name) {
    
        this.name = name;
    }

    public Date getCreateTime() {
    
        return createTime;
    }

    public void setCreateTime(Date createTime) {
    
        this.createTime = createTime;
    }

    @Override
    public String toString() {
    
        return "Video{" +
                "name='" + name + '\'' +
                ", createTime=" + createTime +
                '}';
    }
}

package prototype.Demo1;

import javax.xml.crypto.Data;
import java.util.Date;

/** *  client : clone  */
public class Bilibli {
    
    public static void main(String[] args) throws CloneNotSupportedException {
    
        // Prototype object 

        Date date = new Date();
        Video v1 = new Video(" Cool little ", date);
        System.out.println("v1=>"+v1);
        System.out.println("v1=>hash"+v1.hashCode());

        // Give Way v2 clone v1
        Video  v2 = (Video) v1.clone();
        System.out.println("v2=>"+v2);
        System.out.println("v2=>hash"+v2.hashCode());

    }
}

 Insert picture description here

原网站

版权声明
本文为[Kuxiaoya]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260603342898.html