Back to Hello Algorithm

原型模式(Prototype)

算法读物/设计模式/原型模式.md

latest2.0 KB
Original Source

原型模式(Prototype)

介绍

原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。

Intent

使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。

Class Diagram

<div align="center"> </div>

Implementation

java
public abstract class Prototype {
    abstract Prototype myClone();
}
java
public class ConcretePrototype extends Prototype {

    private String filed;

    public ConcretePrototype(String filed) {
        this.filed = filed;
    }

    @Override
    Prototype myClone() {
        return new ConcretePrototype(filed);
    }

    @Override
    public String toString() {
        return filed;
    }
}
java
public class Client {
    public static void main(String[] args) {
        Prototype prototype = new ConcretePrototype("abc");
        Prototype clone = prototype.myClone();
        System.out.println(clone.toString());
    }
}
html
abc

JDK

你可以通过下方扫码回复【进群】,加入我们的高端计算机学习群!以及下载超过 100 张高清思维导图!

<div align="center"> <a href="https://www.geekxh.com/code.png" style="box-shadow: rgb(210, 210, 210) 0em 0em 0.5em 0px; font-size: 17px;"></a> </div>