原型模式
作者:碳水怪兽👾 发布于:2021/10/10
前言
原型模式是一种创建型模式,是指通过对已有对象(原型)进行复制(拷贝)的方式来创建新对象,这种基于原型来创建对象的方式就是原型设计模式。
通常来说,创建对象的过程包含内存申请、变量赋值等操作,有时变量的指需要通过复杂计算,比如排序,计算hash值,甚至需要通过网络、数据库、文件IO操作,在这种情况下,我们可以使用原型模式,避免每次创建对象都要执行这些高消耗的操作
正文
原型模式类图

代码
-
1.ProtoType接口
public interface ProtoType { ProtoType clone(); } -
ConcreteProtoType类
public class ConcreteProtoType implements ProtoType{ private String filed; public ConcreteProtoType(String filed) { this.filed = filed; } @Override public ProtoType clone() { return new ConcreteProtoType(filed); } @Override public String toString() { final StringBuffer sb = new StringBuffer("ConcreteProtoType{"); sb.append("filed='").append(filed).append('\''); sb.append('}'); return sb.toString(); } } -
Client类
public class Client { public static void main(String[] args) { ConcreteProtoType protoTypeA = new ConcreteProtoType("hello"); ConcreteProtoType protoTypeB = (ConcreteProtoType) protoTypeA.clone(); System.out.println(protoTypeB); } }结尾
原型模式的应用
- JDK#ArrayList
- Spring的bean容器