Java设计模式-(创建型)原型模式

代码仓库:https://gitee.com/yangsiyuan/Design-Pattern

创建型设计模式:聚焦于实例化对象,通常提供一种隐藏创建逻辑的形式,取代直接使用new运算符实例化对象

写在前面的话:

与通过对一个类进行实例化来构造新对象不同的是,原型模式是通过拷贝一个现有对象生成新对象的。浅拷贝实现 Cloneable,重写clone方法;深拷贝是通过实现 Serializable 读取二进制流

1. 定义

原型模式(Prototype Pattern):通过一个原型接口,该接口用于创建当前对象的克隆

  • 核心定义:通过实现Cloneable接口,重写clone()方法,实现对象的浅拷贝。

  • 优点:通过避免创建对象的高消耗,提高性能

  • 缺点:必须实现Cloneable接口;clone方法的实现需要对类的功能进行通盘考虑

  • 应用场景:一般配合工厂模式一起使用,通过 clone 的方法创建一个对象,然后由工厂方法提供给调用者

2. 代码实现

1)定义原型:实现Cloneable接口的抽象类

  1. 实现Cloneable接口,重写clone方法
  2. 定义对象族的相关规范
public abstract class CloneableCar implements Cloneable{

    protected String type;
    private String brandName;
    private String seriesName;
    private String id;
    public String getBrandName() {
        return brandName;
    }
    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }
    public String getSeriesName() {
        return seriesName;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public void setSeriesName(String seriesName) {
        this.seriesName = seriesName;
    }

    // 重写clone方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object clone = null;
        try {
            clone = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
    // 业务方法
    abstract void run();
}

2)定义对象:继承抽象类

  • 实现类1
public class Benz extends CloneableCar{

    public Benz() {
        type = "Benz";
    }

    @Override
    void run() {
        System.out.println("Benz is running!!");
    }
}
  • 实现类2
public class Honda extends CloneableCar{

    public Honda() {
        type = "Honda";
    }

    @Override
    void run() {
        System.out.println("Honda is running!!");
    }
}

3)定义缓存类:将对象缓存为本地map

public class CarCache {
    // 缓存对象
    private static Hashtable<String, CloneableCar> carMap = new Hashtable<String, CloneableCar>();

    // 从map中获取缓存对象
    public static CloneableCar getCar(String carId) throws CloneNotSupportedException {
        CloneableCar cloneableCar = carMap.get(carId);
        return (CloneableCar)cloneableCar.clone();
    }

    public static void loadCache() {
        Benz benz = new Benz();
        benz.setId("1");
        carMap.put(benz.getId(), benz);

        Honda honda = new Honda();
        honda.setId("2");
        carMap.put(honda.getId(), honda);
    }
}

4)测试demo

public class PrototypePatternTest {
    public static void main(String[] args) throws CloneNotSupportedException {
        CarCache.loadCache();
        CloneableCar car1 = CarCache.getCar("1");
        car1.run();

        CloneableCar car2 = CarCache.getCar("2");
        car2.run();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容