原型模式

Updated on in 程序人生 with 0 views and 0 comments

1、简介

原型模式是创建型模式,通过拷贝原型创建新的对象,在重复创建复杂对象占用较多系统资源时,可以考虑使用原型模式。

原型模式使用 clone 能够动态的抽取当前对象运行时的状态并且克隆到新的对象中,新对象就可以在此基础上进行操作而不损坏原有对象;而 new 只能得到一个刚初始化的对象。

2、创建原型

在Java中,需要实现Cloneable接口,并重写Object中的clone方法,如果不实现Cloneable接口,就会抛出CloneNotSupportedException异常

public class User implements Cloneable  {
    private String username;
    private String sex;

    public User(){}
    public User(String userInfo){
        String[] userInfos = userInfo.split("-");
        this.setUsername(userInfos[0]);
        this.setSex(userInfos[1]);
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public User clone() {
        User clone = null;
        try {
            clone = (User)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

3、测试

public class TestPrototype {
    public static void main(String[] args){
        long newObjectStart = System.currentTimeMillis();
        User user1 = new User("问尤龙-男");
        long newObjectEnd = System.currentTimeMillis();
        System.out.println("new创建对象用时:"+(newObjectEnd-newObjectStart));

        long cloneObjectStart = System.currentTimeMillis();
        User user2 = user1.clone();
        long cloneObjectEnd = System.currentTimeMillis();
        System.out.println("clone创建对象用时:"+(cloneObjectEnd-cloneObjectStart));
    }
}

标题:原型模式
作者:wenyl
地址:http://www.wenyoulong.com/articles/2020/12/24/1608775541906.html