I. prototype mode
1. What is prototype mode
Clone
The prototype pattern is a creation pattern. The word "prototype" indicates that there should be a template instance for the schema change. Users copy an object with consistent internal properties from the template object. This process is also called "cloning". The copied instance is what we call "prototype", which is customizable. Prototype mode is often used to create complex or time-consuming instances, because in this case, copying an existing instance can make the program run more efficiently.
2. Prototype mode application scenario
- (1) class initialization needs to digest a lot of resources, including data and hardware resources, which can be avoided through prototype copy.
- (2) an object generated through new needs very tedious data preparation or permission. In this case, prototype mode can be used.
- (3) when an object needs to be provided to other objects for access, and each caller may need to modify its value, you can consider using prototype mode to copy multiple objects for the use of the caller, that is, protective copy.
Many examples in the Spring framework are the use of prototypes.
3. Prototype model UML class diagram (general)
Prototype pattern is mainly used for object replication. Its core is prototype in class diagram. The prototype class requires the following two conditions:
- (1) implement the clonable interface. There is a clonable interface in the java language, which has only one function, that is to inform the virtual machine at runtime that it can safely use the clone method on the class that implements the interface. In the java virtual machine, only the classes that implement this interface can be copied. Otherwise, a CloneNotSupportedException exception will be thrown at runtime.
- (2) override the clone method in the Object class. In Java, the parent class of all classes is the Object class. There is a clone method in the Object class, whose function is to return a copy of the Object, but its scope is of the protected type. General classes cannot be called. Therefore, the Prototype class needs to change the scope of the clone method to the public type.
4. Prototype pattern classification
Demonstration example
/* * Book type plays the role of ConcretePrototype, while Cloneable plays the role of Prototype */ public class Book implements Cloneable { private String title;// Title private ArrayList<String> image = new ArrayList<String>();// Picture name list public Book() { super(); } /** * Override copy method */ @Override protected Book clone() { try { Book book = (Book) super.clone();// book.image=(ArrayList<String>)this.image.clone();//Deep replication return book; } catch (CloneNotSupportedException e) { e.printStackTrace(); } return null; } public ArrayList<String> getImage() { return image; } public void addImage(String img) { this.image.add(img); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } /** * print contents */ public void showBook() { System.out.println("----------------------Start----------------------"); System.out.println("title: " + title); for (String img : image) { System.out.println("image name:" + img); } System.out.println("----------------------End----------------------"); } }
Client code
public class Client02 { public static void main(String[] args) { Book book1 = new Book(); book1.setTitle("Book 1"); book1.addImage("Figure 1"); book1.showBook(); //Make a copy in prototype form Book book2 = book1.clone(); book2.showBook(); book2.setTitle("Book 2"); book2.addImage("Figure 2"); book2.showBook(); //Restore printed book again book1.showBook(); } }
5. The prototype mode is divided into shallow replication and deep replication
- Shallow copy - only the basic type of data is copied, and the reference type data will also be referenced after copying. We call this kind of copy (shallow copy) shallow copy. In other words, shallow copy only points to the memory address to be copied. If the object in the original address is changed, the shallow copied object will change accordingly.
- Deep copy - opens up a new memory address in the computer to hold the copied object.
II. Strategic model
1. What is the strategic mode
A series of algorithms are defined, and each algorithm is encapsulated, and they can be replaced each other. The strategy pattern makes the algorithm independent of the customers who use it.
2. The strategic model consists of three roles
Application scenario of policy mode
The purpose of policy pattern is to encapsulate each algorithm or logic into a separate class with a common interface for a group of algorithms or logic, so that they can be replaced with each other. The policy mode enables the algorithm or logic to change without affecting the client. When it comes to the policy mode, we have to mention the OCP(Open Closed Principle) opening and closing principle, that is, opening to extension and closing to modification. The emergence of the strategy mode well explains the opening and closing principle and effectively reduces the branch statements.
3. Policy mode code
This code can be divided into three strategies by simulating the different discount dynamics of shopping cart of different members: junior member, intermediate member and senior member.
//Policy patterns define abstract methods all supporting public interfaces abstract class Strategy { // Algorithm method abstract void algorithmInterface(); } class StrategyA extends Strategy { @Override void algorithmInterface() { System.out.println("algorithm A"); } } class StrategyB extends Strategy { @Override void algorithmInterface() { System.out.println("algorithm B"); } } class StrategyC extends Strategy { @Override void algorithmInterface() { System.out.println("algorithm C"); } } // Use context to maintain algorithm policy class Context { Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void algorithmInterface() { strategy.algorithmInterface(); } } class ClientTestStrategy { public static void main(String[] args) { Context context; context = new Context(new StrategyA()); context.algorithmInterface(); context = new Context(new StrategyB()); context.algorithmInterface(); context = new Context(new StrategyC()); context.algorithmInterface(); } }
3. Observer mode
1. What is observer mode
Observer mode is a kind of behavioral model, which focuses on the interaction between objects in the system, solves the communication and cooperation between objects in the system at runtime, and further clarifies the responsibilities of objects. In contrast, the creation mode focuses on the creation process of objects, while the structural mode focuses on the combination of objects and classes.
2. Responsibilities of the model
Observer mode is mainly used for 1-to-N notification. When the state of an object changes, he needs to inform a series of objects in time to make them corresponding. There are two ways to achieve this:
- Tweet: every time, the notification will be broadcast to all observers, and all observers can only receive it passively.
- RA: as long as the observer knows the situation, he or she can decide when and what to get.
3. Implementation of the model
//Observer interface, used to store shared methods of observers public interface Observer { // Observer method void update(Subjecct subjecct); } //Parent class of observation object public class Subjecct { //Storage set for observers private List<Observer> list = new ArrayList<>(); // Register observer method public void registerObserver(Observer obs) { list.add(obs); } // Delete observer method public void removeObserver(Observer obs) { list.remove(obs); this.notifyAllObserver(); } // Notify all observers of updates public void notifyAllObserver() { for (Observer observer : list) { observer.update(this); } } } //Realization of specific observer object public class RealObserver extends Subjecct { //Properties of observed objects private int state; public int getState(){ return state; } public void setState(int state){ this.state=state; //Subject object (target object) value changed this.notifyAllObserver(); } } public class Client { public static void main(String[] args) { // Target object RealObserver subject = new RealObserver(); // Create multiple observers ObserverA obs1 = new ObserverA(); ObserverA obs2 = new ObserverA(); ObserverA obs3 = new ObserverA(); // Register to observation queue subject.registerObserver(obs1); subject.registerObserver(obs2); subject.registerObserver(obs3); // Change State state subject.setState(300); System.out.println(obs1.getMyState()); System.out.println(obs2.getMyState()); System.out.println(obs3.getMyState()); // Change State state subject.setState(400); System.out.println(obs1.getMyState()); System.out.println(obs2.getMyState()); System.out.println(obs3.getMyState()); } }
4. Observer mode application scenario
When associating a behavior scenario, it should be noted that the association behavior is separable, not a "composite" relationship. Event multi-level trigger scenario.
Cross system message exchange scenarios, such as message queues, event bus processing mechanisms.
Personal blog Snail