设计模式——原型模式(Prototype Pattern)

文章目录

  • 一、原型模式定义
  • 二、例子
    • 2.1 利用Cloneable克隆接口实现的。
      • 2.1.1 定义可复制自身的User类
      • 2.1.2 定义原型工厂PrototypeFactory
      • 2.1.3 使用
    • 2.2 JDK源码——ArrayList
  • 三、其他设计模式

一、原型模式定义

类型: 创建型模式
目的: 用于创建重复的对象,同时又能保证性能。

二、例子

2.1 利用Cloneable克隆接口实现的。

2.1.1 定义可复制自身的User类

public class User implements Cloneable {
    protected String id;
    protected String name;

    public User(String id, String name) {
        this.id = id;
        this.name = name;
    }
    
    public Object clone() {
        Object clone = null;
        try {
            clone = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}

2.1.2 定义原型工厂PrototypeFactory

public class PrototypeFactory{

    private static User prototypeUser;

    public static User setPrototypeUser(User prototypeUser){
        prototypeUser = prototypeUser;
    }
    public static User getPrototypeUser(){
        if(prototypeUser == null){
            prototypeUser = new User("0","xxxx");
        }
        return (User) prototypeUser.clone();
    }
}

2.1.3 使用

public static void main(String[] args) throws Exception{

	PrototypeFactory.setPrototypeUser(new User("root","admin"));

	User prototypeUser1 =  PrototypeFactory.getPrototypeUser();
	User prototypeUser2 =  PrototypeFactory.getPrototypeUser();
	User prototypeUser3 =  PrototypeFactory.getPrototypeUser();
}

除了clone,还可以使用反序列化和拷贝工具实现原型模式。

2.2 JDK源码——ArrayList

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
	    public Object clone() {
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }
}

三、其他设计模式

创建型模式
结构型模式

  • 1、设计模式——装饰器模式(Decorator Pattern)+ Spring相关源码

行为型模式

  • 1、设计模式——访问者模式(Visitor Pattern)+ Spring相关源码
  • 2、设计模式——中介者模式(Mediator Pattern)+ JDK相关源码
  • 3、设计模式——策略模式(Strategy Pattern)+ Spring相关源码
  • 4、设计模式——状态模式(State Pattern)
  • 5、设计模式——命令模式(Command Pattern)+ Spring相关源码
  • 6、设计模式——观察者模式(Observer Pattern)+ Spring相关源码
  • 7、设计模式——备忘录模式(Memento Pattern)
  • 8、设计模式——模板方法模式(Template Pattern)+ Spring相关源码
  • 9、设计模式——迭代器模式(Iterator Pattern)+ Spring相关源码
  • 10、设计模式——责任链模式(Chain of Responsibility Pattern)+ Spring相关源码
  • 11、设计模式——解释器模式(Interpreter Pattern)+ Spring相关源码

你可能感兴趣的:(Programming,Concepts,设计模式,原型模式,spring,prototype)