Design Pattern (6) Prototype Pattern

What is Prototype Pattern

Usually, we will use the new something() method to create an instance, but the following situations may not support our creation in this way. For example:

  1. There are many kinds of objects, and it is impossible to integrate them into one class. There
    are too many objects to be processed. If you treat them as one class, you need to write many class files.
  2. Difficult to generate instances from classes
    The process of generating class instances is too complex, and it is difficult to generate instances from instances. For example, if you use the mouse to create a graphics instance in the graphics editor, if you want to generate an instance that is exactly the same as the instance created by the previous user operation, you will first save the created instance, and then generate a new instance by copying
  3. I want to decouple the framework from the produced instance.
    I want the framework that produces the instance not to depend on the concrete class. At this time, you cannot specify the class name to generate an instance, but register a prototype in advance, and then generate a new instance by copying the instance.

In the design pattern, the prototype pattern is a creational design pattern, which generates new instances based on instance prototypes and instance models.

Cloneable interface and Clone method

Cloneable is a marker interface. There is no abstract method in this interface. Implementing this interface means that the implementation class of this interface can use Clone

package java.lang;

public interface Cloneable {
    
    
}

The Clone method is a method in the Object class. It can copy a new instance based on an instance. The Object class is the parent class of all classes, so all classes have the Clone method. However, if an instance of a certain class wants to To use this method, the class must implement the Cloneable interface first , otherwise CloneNotSupportedException will be thrown when using it .

protected native Object clone() throws CloneNotSupportedException;

The Clone method performs a shallow copy , which directly copies the field values ​​​​of the copied instance to the new instance. For example, if an array is stored in the field, using Clone to copy will only copy the reference of the array, and will not copy the elements in the array one by one. If Clone can't meet the demand, Clone can be rewritten

example

Examples are displaying strings boxed or underlined

Manager

package CreationPattern.PrototypeMode;

import java.util.HashMap;

/**
 * 管理并复制实例
 */

public class Manager {
    
    
    private HashMap map = new HashMap();

    public void register(String name, Product proto) {
    
    
        map.put(name, proto);
    }

    public Product create(String protoName) {
    
    
        Product product = (Product) map.get(protoName);
        return product.createClone();
    }
}

Product

package CreationPattern.PrototypeMode;

/**
 * 产品接口
 */

public interface Product extends Cloneable {
    
    
    void use(String s);

    Product createClone();
}

MessageBox

package CreationPattern.PrototypeMode;

/**
 * 方框信息
 */

public class MessageBox implements Product {
    
    
    private char decoChar;

    public MessageBox(char decoChar) {
    
    
        this.decoChar = decoChar;
    }

    @Override
    public void use(String s) {
    
    
        int len = s.getBytes().length;
        for (int i = 0; i < len + 4; i++) {
    
    
            System.out.print(decoChar);
        }
        System.out.println();

        System.out.println(decoChar + " " + s + " " + decoChar);

        for (int i = 0; i < len + 4; i++) {
    
    
            System.out.print(decoChar);
        }
        System.out.println();
    }

    @Override
    public Product createClone() {
    
    
        Product p = null;
        try {
    
    
            p = (Product) clone();
        } catch (CloneNotSupportedException e) {
    
    
            throw new RuntimeException(e);
        }
        return p;
    }
}

UnderlinePen

package CreationPattern.PrototypeMode;

/**
 * 下划线信息
 */

public class UnderlinePen implements Product {
    
    
    private char ulChar;

    public UnderlinePen(char ulChar) {
    
    
        this.ulChar = ulChar;
    }

    @Override
    public void use(String s) {
    
    
        int len = s.getBytes().length;

        System.out.println("\"" + s + "\"");

        for (int i = 0; i < len; i++) {
    
    
            System.out.print(ulChar);
        }
        System.out.println();
    }

    @Override
    public Product createClone() {
    
    
        Product p = null;
        try {
    
    
            p = (Product) clone();
        } catch (CloneNotSupportedException e) {
    
    
            throw new RuntimeException(e);
        }
        return p;
    }
}

result
insert image description here

Summarize

Usually, we use new something() to create an instance, but in this way, the class name must be specified, but sometimes there is a need to produce an instance without specifying the class name, or there are many types of objects, and Or if you want to decouple the framework and generate instances, then we need to use the prototype mode.

Guess you like

Origin blog.csdn.net/weixin_43636205/article/details/129528852