"Design Patterns" Prototype Patterns

"Design Patterns" Basic Principles of Design Patterns
"Design Patterns" Singleton Patterns "
Design Patterns" Factory Patterns
"Design Patterns" Prototype Patterns "
Design Patterns" Builder Patterns "Design Patterns
" Adapter Patterns "Design
Patterns" Bridge Patterns
"Design Patterns" "Decorator Mode
" Design Mode" Composition Mode
"Design Mode" Appearance Mode "Design Mode"
Flyweight Mode "Design Mode" Proxy Mode "
Design Mode
" Template Method Mode
"Design Mode" Command Mode

"Design Patterns" Prototype Patterns


Definition :

  • Prototype mode refers to the use of prototype instances to specify the type of object to be created, and by copying these prototypes, new objects are created .
  • It is a creational design pattern that allows an object to create another customizable object without knowing the details of the creation.
  • Its working principle is: by passing a prototype object to the object to be created, the object to be created implements creation by requesting the prototype object to copy itself, ie 对象.clone().

A UML class diagram of the prototype pattern looks like this:

insert image description here
in:

  • Prototype represents a prototype class, declaring an interface that clones itself
  • ConcretePrototype represents a specific prototype class and implements an operation of cloning itself
  • Client makes a prototype object clone itself to create a new object (with the same properties)

Notes on the Prototype pattern :

  • When creating a new object is more complicated, you can use the prototype mode to simplify the object creation process and improve efficiency.
  • Instead of reinitializing the object, it dynamically obtains the runtime state of the object.
  • If the original object properties change, the other cloned objects change too, without modifying the code.
  • The prototype mode uses shallow copy to clone objects by default. If you want to implement deep copy, it is recommended to use object serialization.

Now there is a sheep whose name is tom, age is 1, and color is white. You need to write a program to create 10 sheep with the same attributes as tom sheep.

Using the traditional way to analyze the problem, its UML diagram is as follows:
insert image description here
SheepClass

public class Sheep {
    
    
    private String name;
    private int age;
    private String color;

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    public String getColor() {
    
    
        return color;
    }

    public void setColor(String color) {
    
    
        this.color = color;
    }

    public Sheep(String name, int age, String color) {
    
    
        this.name = name;
        this.age = age;
        this.color = color;
    }
}

Clientkind

public class Client {
    
    
    public static void main(String[] args) {
    
    
        Sheep sheep = new Sheep("tom", 1, "白色");
        Sheep sheep1 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
        Sheep sheep2 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
        Sheep sheep3 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
        //...
    }
}

The advantage of the traditional implementation is that it is easy to operate and easy to understand. However, when creating a new object, it is always necessary to retrieve the properties of the original object. If the created object is more complex, the efficiency is relatively low. In addition, the object always needs to be reinitialized, instead of dynamically obtaining the runtime state of the object, which is not flexible enough.

To solve this problem using the prototype mode, you need to let Sheepthe class implement the methodCloneable in the interface , so that the class can be copied, and the program has higher efficiency and scalability.cloneSheep

Sheepkind

public class Sheep implements Cloneable{
    
    
    private String name;
    private int age;
    private String color;
    public Sheep friend;  //默认是浅拷贝,直接拷贝地址
    private String address = "山羊";

    @Override
    public Object clone() {
    
    
        Sheep sheep = null;
        try {
    
    
            sheep = (Sheep) super.clone(); //默认是浅拷贝,直接拷贝地址
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return sheep;
    }
    
    @Override
    public String toString() {
    
    
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
    
    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    public String getColor() {
    
    
        return color;
    }

    public void setColor(String color) {
    
    
        this.color = color;
    }
    public Sheep(String name, int age, String color) {
    
    
        this.name = name;
        this.age = age;
        this.color = color;
    }
}

Clientkind

public class Client {
    
    
    public static void main(String[] args) {
    
    
        Sheep sheep = new Sheep("tom", 1, "白色");
        sheep.friend = new Sheep("jack", 2, "黑色");
        Sheep sheep1 = (Sheep) sheep.clone(); //sheep1 != sheep,但是 sheep.friend==sheep1.friend
        Sheep sheep2 = (Sheep) sheep.clone(); //sheep2 != sheep,但是 sheep.friend==sheep2.friend
        Sheep sheep3 = (Sheep) sheep.clone(); 
    }
}

The above is the specific implementation of using the prototype pattern to solve the problem of cloning sheep.

The prototype mode is also applied in the Spring framework, and the methodAbstractBeanFactory part code in the class is as follows:doGetBean

protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
    
    
	if (mbd.isSingleton()) {
    
    
         sharedInstance = this.getSingleton(beanName, () -> {
    
    
              try {
    
    
                  return this.createBean(beanName, mbd, args);
              } catch (BeansException var5) {
    
    
                  this.destroySingleton(beanName);
                  throw var5;
              }
          });
          bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
      } else if (mbd.isPrototype()) {
    
    
          var11 = null;

          Object prototypeInstance;
          try {
    
    
              this.beforePrototypeCreation(beanName);
              prototypeInstance = this.createBean(beanName, mbd, args);
          } finally {
    
    
              this.afterPrototypeCreation(beanName);
          }

          bean = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
      } else {
    
    
      	//...
      }
      //...
}

Guess you like

Origin blog.csdn.net/weixin_43252521/article/details/127294339