最近在做业务实现的时候,为了通过提升机器来降低开发人员的难度和要求,于是在架构设计上严格按照面向对象去做的。
进而在内存中同一个类处理业务的对象就会很多,为了解决对象复制过程中降低耦合的要求,研究了原型模式。
原型模式(ProtoTYpe),用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

package com.a7DesignPattern.a1CreatType.a4Prototype;
/**
* 功能描述:浅复制client
*
* @Author:makang
* @Date: 2021/4/30 17:21
*/
public class Client {
public static void main(String[] args) {
ConcretePrototype1 prototype1 = new ConcretePrototype1();
prototype1.setId("1111111");
ConcretePrototype1 prototype2 = (ConcretePrototype1)prototype1.clone();
prototype2.setId("222222222");
System.out.println(prototype2.getId());
}
}
package com.a7DesignPattern.a1CreatType.a4Prototype;
/**
* 功能描述:
*
* @Author:makang
* @Date: 2021/4/30 17:19
*/
public abstract class Prototype implements Cloneable {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
package com.a7DesignPattern.a1CreatType.a4Prototype;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
/**
* 功能描述:
*
* @Author:makang
* @Date: 2021/4/30 17:20
*/
public class ConcretePrototype1 extends Prototype{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
// @Override
public Object clone() {
ConcretePrototype1 concretePrototype1 = null;
try{
concretePrototype1 = (ConcretePrototype1) super.clone();
}catch (Exception e){
}
return concretePrototype1;
}
}
package com.a7DesignPattern.a1CreatType.a4Prototype;
/**
* 功能描述:
*
* @Author:makang
* @Date: 2021/4/30 17:21
*/
public class ConcretePrototype2 extends Prototype{
@Override
public Prototype clone() {
return (Prototype) this.clone();
}
}
原型模式中的具体原型类concretePrototype1和concretePrototype2有横向纵向两层含义:
通过对于原型模式的梳理和再探的过程,进一步强化了面向对象中面对抽象编程和面对接口编程这件事;而通过原型模式深浅复制的不同场景的运用使得迪米特法则的落地也更加的彻底。