原型模式:(Prototype)
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
创建很多重复的对象,不影响性能;
比如我们查询相同的数据, 如果 mybatis 查询数据库,很多相同的记录,是多个相同的 user
原型模式,主要是利于缓存,-->每次返回一个不一样的克隆体供我们使用
本体给外部返回一个克隆体
package com.atlucas.creation.prototype;
import javax.jws.soap.SOAPBinding;import java.util.HashMap;
/** * @author Lucas * @create 2021-11-18 16:38 * @description 测试原型模型,创建相同的属性对象,但不会影响性能 */public class TestProtoType { public static HashMap <String,User> prototypeCache=new HashMap<String, User>();
public User getUser() throws CloneNotSupportedException {
//缓存,相同的数据再缓存中拿取出来
/** * 比如我们查询一个名称,给我们返回一个数据记录 */
TestProtoType type = new TestProtoType();
//缓存中不存在 if (!prototypeCache.containsKey("lucas")) { //从数据库取出来 User user = TestProtoType.getUserfromDB(); return user; } else {
User user = prototypeCache.get("1"); //拿到原型之后--->实现克隆体 User clone = (User) user.clone(); return clone; }
}
//获取数据库的数据对象 private static User getUserfromDB() throws CloneNotSupportedException {
System.out.println("获取数据库中的对象"); User user=new User(); user.setUserName("lucas"); user.setAge(23); user.setUserID("10086123"); //放入缓存,原型-->克隆体,所以每次获取都会创建一个克隆体 User put = prototypeCache.put("1", (User) user.clone()); return user; }
public static void main(String[] args) throws CloneNotSupportedException { TestProtoType t1=new TestProtoType(); User user = t1.getUser();
TestProtoType t2=new TestProtoType(); User user1 = t2.getUser(); System.out.println(user==user1); }}
复制代码
评论