设计模式之原型模式

乐百川

关注

阅读 116

2022-02-12

针对每一次连接都创建一个重复对象。
首先创造一个抽象类实现Cloneable接口,重写clone方法。

public abstract class Person implements Cloneable{

    private String name;
    protected String type;
    abstract void print();

    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object clone=null;
        try{
            clone=super.clone();
        }catch (CloneNotSupportedException e){
            e.printStackTrace();
        }
        return clone;
    }
}

创建抽象类的实体类

public class Student extends Person{
    public Student() {
        type="Student";
    }
    @Override
    void print() {
        System.out.println("我是学生");
    }
}
public class Teacher extends Person{
    public Teacher() {
        type="Teacher";
    }

    @Override
    void print() {
        System.out.println("我是教师");
    }
}

public class Nurse extends Person{
    public Nurse() {
        type="Nurse";
    }

    @Override
    void print() {
        System.out.println("我是护士");
    }
}

将实体类clone存放到hashtable中

public class PersonCache {
    private static Hashtable<String,Person> personMap=new Hashtable<>();

    public static Person getPerson(String name) throws CloneNotSupportedException {
        Person person = personMap.get(name);
        return (Person) person.clone();
    }

    public static void loadCache(){
        Student student = new Student();
        System.out.println("a地址:"+student.hashCode());
        student.setName("a");
        personMap.put(student.getName(),student);

         Teacher teacher = new Teacher();
         teacher.setName("b");
         personMap.put(teacher.getName(),teacher);

        Nurse nurse = new Nurse();
        nurse.setName("c");
        personMap.put(nurse.getName(),nurse);
    }

    public static void main(String[] args) throws CloneNotSupportedException {
        PersonCache.loadCache();
        Person clonePerson01 = PersonCache.getPerson("a");
        System.out.println("a clone 地址:"+clonePerson01.hashCode());
        System.out.println(clonePerson01.getType());
        Person clonePerson02 = PersonCache.getPerson("b");
        Person clonePerson03 = PersonCache.getPerson("c");
    }
}

通过hashcode可以知道是两个不同的对象。
原型模式主要就是实现cloneable接口,重写clone方法实现原型模式。

精彩评论(0)

0 0 举报