Android设计模式:原型设计模式

2018-09-26  本文已影响0人  kjy_112233

(1)原型模式实现

public class Person implements Cloneable {
    private int age;
    private boolean sex;
    private String name;

    @Override
    public Object clone() {
        Person person;
        try {
            person = (Person) super.clone();
            person.age = this.age;
            person.sex = this.sex;
            person.name = this.name;
            return person;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isSex() {
        return sex;
    }

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

    public String getName() {
        return name;
    }

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

    @NonNull
    @Override
    public String toString() {
        return "Person{" + "name='" + name + ", sex=" + sex + ", age=" + age + '}';
    }
}
        Person person = new Person();
        person.setName("小李");
        person.setSex(true);
        person.setAge(22);
        System.out.println(person);
        Person person1 = (Person) person.clone();
        System.out.println(person1);
        person1.setName("小张");
        System.out.println(person);
        System.out.println(person1);
    @Override
    public Object clone() {
        Person person = null;
        try {
            person = (Person) super.clone();
            person.name = this.name;
            person.sex = this.sex;
            person.age = this.age;
            person.height = this.height;
            person.hobbies = this.hobbies;
            return person;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public Object clone() {
        Person person = null;
        try {
            person = (Person) super.clone();
            person.name = this.name;
            person.sex = this.sex;
            person.age = this.age;
            person.height = this.height;
            person.hobbies = (ArrayList<String>) this.hobbies.clone();
            return person;
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

优点

缺点

上一篇下一篇

猜你喜欢

热点阅读