当先锋百科网

首页 1 2 3 4 5 6 7

原型模式

原型模式是指通过原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象,简单来说就是克隆当前的对象。

首先创建一个实现了Cloneable接口的抽象类Car

public abstract class Car implements Cloneable{
    private String name;
    protected String type;

    abstract void run();
    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }
    
    public Object clone(){
        Object clone = null;
        try {
            clone = super.clone();
        }catch (CloneNotSupportedException e){
            e.printStackTrace();
        }
        return clone;
    }
    
}

然后创建实体类

public class SUV extends Car{
    public SUV(){
        type = "SUV";
    }
    @Override
    void run() {
        System.out.println("SUV");
    }
}
public class Tractor extends Car{
    public Tractor() {
        type = "Tractor";
    }

    @Override
    void run() {
        System.out.println("Tractor");
    }
}

创建一个CarCache类

public class CarCache {
    private static Hashtable<String, Car> carMap
            = new Hashtable<String, Car>();

    public static Car getCar(String carName) {
        Car cachedCar = carMap.get(carName);
        return (Car) cachedCar.clone();
    }

    public static void loadCache() {
        SUV suv = new SUV();
        suv.setName("1");
        carMap.put(suv.getName(),suv);

        Tractor tractor = new Tractor();
        tractor.setName("2");
        carMap.put(tractor.getName(),tractor);
    }
}

通过CarCache获取存储在hashtable中的车的克隆

public static void main(String[] args) {
    CarCache.loadCache();

    Car car1 = CarCache.getCar("1");
    System.out.println("Car:"+car1.getType());
    Car car2 = CarCache.getCar("2");
    System.out.println("Car:"+car2.getType());
}

输出结果:

Car:SUV
Car:Tractor