原型设计模型

public interface IGetObject {

    //复制一个对象的方法
    Object clone();
}

 

public class Hero implements IGetObject{

    private  int id;
    private String name;

    public Hero() {
    }


    //创建一个构造器,用来配合返回对象
    public Hero(Hero hero) {
        this.id = hero.getId();
        this.name = hero.getName();
    }

    //这个方法的目的是复制当前的一个Hero对象
    @Override
    public Object clone() {

        return new Hero(this);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Hero{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
public class Test {

    public static void main(String[] args) {
        Hero hero =new Hero();
        hero.setId(1001);
        hero.setName("乔妹");
        //instanceof
        Hero clone =(Hero) hero.clone();

        System.out.println(hero==clone);//false
        System.out.println(hero);
        System.out.println(clone);

    }
}

 

 

 */                 //1.要实现Object中的克隆方法必须实现克隆接口Cloneable
public class Hero1 implements Cloneable{
    private int id;
    private String name;

    @Override//Object中的克隆方法
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public Hero1() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Hero1{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
    public static void main(String[] args) throws CloneNotSupportedException {

        Hero1 hero1 =new Hero1();
        hero1.setId(1001);
        hero1.setName("小乔");
        Hero1 clone = (Hero1) hero1.clone();

        System.out.println(hero1==clone);//false
        System.out.println(clone);
        System.out.println(hero1);

        System.out.println(hero1.hashCode()==clone.hashCode());//false

    }
}

 

posted on 2021-12-08 17:49  无心睡眠A8  阅读(31)  评论(0)    收藏  举报