This is the 26th day of my participation in the August More Text Challenge

Author: Tom Brother wechat official account: Micro technology

Hi, I’m Tom

In the face of complex business scenarios and ever-changing customer needs, how to respond to changes with one change and achieve rapid implementation with the minimum development cost, while ensuring the system has a low complexity, can ensure the continuous iteration ability of the system, so that the system has high scalability.

These are the basic internal skills that a qualified architect must practice, but how to practice this magic skill??

I have made a summary of commonly used software design patterns as follows:

(Considering the large content, in order to facilitate reading, the software design pattern series (a total of 23) is divided into four articles, each article explains six design patterns, using different colors to facilitate quick digestion and memory)

Previous review:

  • What do Ali architects do in the face of complex business architecture? (Issue 1)

This paper mainly explains the bridge mode, combination mode, decoration mode, facade mode, agent mode, responsibility chain mode

This PDF includes Java basics, Java concurrency, JVM, MySQL, Redis, Spring, MyBatis, Kafka, design patterns and other interview questions. Links to download address: baidu cloud: pan.baidu.com/s/1XHT4ppXT… Extraction code: s3AB

1. Bridge mode

Nature generally consists of substance and action. Of course, in order to improve the scalability of the system, they can be abstracted separately, and then describe their dependencies in abstract classes.

Definition:

Separate the abstract part from its implementation part so that they can all change independently.

What scenarios use bridge mode?

  • A class has two (or more) dimensions that vary independently, and both (or more) dimensions need to be extended independently.

  • The bridge pattern is especially useful for systems that do not want to use inheritance or where the number of system classes increases dramatically due to multiple levels of inheritance.

Core ideas:

  • Abstract entity: An abstract classification of definitions. Such as: the person

  • Concrete entity: A subclass entity that inherits an abstract entity. For example: Chinese, Americans, Koreans

  • Abstract behavior: Defines the multiple behaviors that exist in an abstract entity. For example: learning Chinese, eating hamburgers

  • Concrete behavior: Concrete algorithms that implement abstract behavior. For example, Chinese learn Chinese and Americans eat hamburgers

Code examples:

/** * @author 微信 号 : abstract entity */ public abstract class abstractactentity {protected behavior AbstractBehavior; public AbstractEntity(AbstractBehavior abstractBehavior) { this.abstractBehavior = abstractBehavior; } public abstract void out(); } /** * public interface AbstractBehavior {public String action(String name); } /** * public implements AbstractBehavior {@override public String action(String name) { Equals (name)) {return equals(name); } else if (" American ".equals(name)) {return "eat hamburger "; } return null; }}Copy the code

The bridging pattern separates abstractions from abstractions, and concrete implementation classes depend on abstractions. The separation of abstractions indirectly completes the decoupling of concrete classes from concrete classes, which are combined or aggregated using abstractions rather than multiple inheritance. The essence is to separate the entity and behavior of an object and then evolve independently based on these two dimensions.

Applicable scenarios:

  • When splitting complex class objects. When a class contains a large number of objects and methods, it is neither easy to read nor easy to modify.

  • When you want to scale from multiple independent dimensions. For example, a system functional and non-functional perspective, a business or technical perspective, etc.

  • At run time, compose different components

2. Combination mode

Definition:

The composite pattern, also known as the global pattern, treats a group of similar objects as a single object and then groups the objects into a tree structure to represent the entire hierarchy.

There are two key points: 1. Hierarchical tree structure and 2. Unified service to simplify operations

Core ideas:

  • Abstract Components (AbstractNode) : Define unified operations that need to be implemented.

  • CompositeNode: A derivative of an abstract component that contains several child nodes (other CompositeNode or leaf nodes).

  • LeafNode: a subclass of an abstract component that has no children under it.

Code examples:

public abstract class AbstractNode { public abstract void add(AbstractNode abstractNode); public abstract void remove(AbstractNode abstractNode); public abstract void action(); } public class CompositeNode extends AbstractNode { private Long nodeId; private List<AbstractNode> childNodes; Public CompositeNode(Long nodeId, List<AbstractNode> childNodes) {this.nodeId = nodeId; this.childNodes = childNodes; } @Override public void add(AbstractNode abstractNode) { childNodes.add(abstractNode); } @Override public void remove(AbstractNode abstractNode) { childNodes.remove(abstractNode); } @Override public void action() { for (AbstractNode childNode : childNodes) { childNode.action(); } } } public class LeafNode extends AbstractNode { private Long nodeId; public LeafNode(Long nodeId) { this.nodeId = nodeId; } public void add(AbstractNode AbstractNode) {public void add(AbstractNode AbstractNode); } @override public void remove(AbstractNode AbstractNode) { } @override public void action() {system.out.println (" nodeId: "+ nodeId); }}Copy the code

A leaf node cannot add or delete child nodes, so the corresponding method is empty.

Composite patterns essentially encapsulate the inherent variations of complex structures, allowing users to use structures between objects as a unified whole. Data structure support tree structure, ring structure, network structure. Such as our common depth first search, breadth first search is to use this model.

Applicable scenarios:

  • A set of objects is managed according to some sort of hierarchy. For example: manage folders and files, manage the goods under the order.

  • Objects in complex structures need to be treated in a uniform manner

  • Rapidly extend object composition.

In the beginning, mobile phones were classified by brand, but now the business is classified by price dimension. We only need to introduce new branch nodes and build portfolio relations according to the new dimension.

3. Decoration mode

Definition:

Dynamically adding new responsibilities and behaviors to an existing object without changing its structure is equivalent to wrapping an existing object.

Core ideas:

  • Abstract Component: Decorator base class that defines the basic functionality of the Component

  • ConcreteComponent: concrete implementation of an abstract component

  • Decorator: Contains a reference to an abstract component

  • ConcreteDecorator: A subclass of an abstract decorator that overwrites component interface methods while adding additional functionality.

Code examples:

public abstract class Component { public abstract void execute(); } public class ConcreteComponent extends Component {@override public void execute() {system.out.println (" ConcreteComponent extends Component {@override public void execute() {system.out.println (" ConcreteComponent extends Component {@override public void execute() {system.out ConcreteComponent invoke !" ); } } public class Decorator extends Component { protected Component component; public Decorator(Component component) { this.component = component; } @Override public void execute() { component.execute(); } } public class ConcreteDecorator extends Decorator { public ConcreteDecorator(Component component) { super(component);  } @override public void execute() {system.out.println (" ConcreteDecorator invoke! ); super.execute(); }}Copy the code

Decorator mode is essentially adding new functionality to an existing class that can’t be modified, and it can be easily undone.

Applicable scenarios:

  • Objects can be used without modifying the code, and you want to add additional functionality to the object at run time

  • By organizing business logic into hierarchies, you can create a decoration for each layer that combines various kinds of logic into objects at run time. Because these objects all follow a common interface, client code can use these objects in the same way.

  • Scenarios where inheritance from extended classes is not supported. For example, the final keyword restricts the further extension of a class, which can be wrapped with a decorator to make it extensible.

4. Facade mode

Definition:

The facade pattern provides a high-level interface that requires communication between the outside and inside of a subsystem through a unified object, making the subsystem easier to use.

The facade mode requires us to use a unified standard to interact with the system. For example, we basically choose SLF4J framework to print logs, which integrates log4j, LOG4j2, CommonLog and other log frameworks internally, simplifying our development costs.

Core ideas:

  • Facade system. Receives external requests and forwards them to the appropriate subsystem for processing

  • Subsystem. Represents a functional implementation within a domain, or a specific subinterface implementation, such as an order, payment, etc., that specifically handles tasks assigned by the facade system.

In short, a facade role was introduced to simplify the interaction between clients and subsystems, providing a unified entry point for complex subsystem calls.

Many people may have questions, this is not the agency model?

Facade mode may represent multiple interfaces, whereas proxy mode typically represents only one interface.

Business scenarios:

Mobile Internet, we are used to online payment, I believe many people have heard such a sentence in the payment, “wechat pay or Alipay”, merchants according to user feedback and then targeted selection of payment channels.

Is tedious, in order to solve this problem, the market has a polymerization pay (do very good in this field is money), the whole business model is the day to tell facade pattern, no matter what software you use to pay, as long as the qr code can open the payment, receive money the underlying analytical qr code identification, and automatically according to the results of the scan adapter corresponding collection channels, Complete the user’s deduction action, really bring good user experience.

Advantages:

  • Simplify complex systems and provide unified interface specifications. For example, JPA provides a unified Java persistence layer API that is suitable for a variety of storage systems.

  • Complex business logic is digested by internal subsystems, and external callers do not need to modify it frequently as long as the external interface specifications remain unchanged

  • Good scalability, similar to the SPI architecture, supports horizontal scaling.

  • High smooth transition. For example: we want to upgrade the old system architecture, develop a series of new interfaces to replace the original old interface, the transition period requires new and old gray testing, flow switching, smooth upgrade, you can use this mode. Facade mode is a powerful tool in compatibility with multiple systems and system reconstruction.

5. Proxy mode

Definition:

Provide a proxy for other objects to control access to that object

Realistic scenario:

  • Real estate agents

  • contractor

Core ideas:

  • AbstractSubject class: defines interface methods for use by clients

  • RealSubject: Interface methods that implement abstract topic classes

  • Proxy class: Implements an interface method that abstracts the topic class, contains the logic of the topic implementation class, and also contains some extension operations of its own.

The proxy pattern is similar to the adapter pattern. But the adapter mode converts to the new interface, while the proxy mode does not change the original interface.

Code examples:

*/ public interface AbstractSubject {void execute(); } public class implements AbstractSubject {@override public void execute() {system.out.println (" implements subject ", "implements subject", "implements subject") { I'm going to work hard!" ); } } public class Proxy implements AbstractSubject { private AbstractSubject abstractSubject; public Proxy(AbstractSubject abstractSubject) { this.abstractSubject = abstractSubject; } @override public void execute() {system.out.println ("... ); abstractSubject.execute(); }}Copy the code

It can be divided into static proxy and dynamic proxy according to user responsibilities.

  • Static proxy, proxy class need to write their own code to complete.

  • Proxyinstance (ClassLoader,Class<? > [] interfaces, generate InvocationHandler h) method.

  • JDK implementations of proxies, whether static or dynamic, are interface oriented. CGLib can be unlimited.

Advantages:

  • Responsibilities clear

  • High extension, as long as the interface is implemented, can use proxy

  • Intelligent, dynamic proxy

  • Reduces the direct coupling of objects

Applicable scenarios:

  • Remote proxy. Remote objects cannot be manipulated directly. For example, Dubbo and gRPC provide remote services. When the client calls, operations such as parameter assembly, serialization, and network transmission are required. These general logic can be encapsulated in the proxy, and the client calls the proxy object to access the remote service, just as convenient as calling the local object.

  • Protect the agent. When the client accesses the original object through the proxy object, the proxy object determines whether the client has access permission based on the rules. Example: firewall

  • Log agent. For example: log monitoring, normal business access, call proxy, add some additional logging functions.

  • Virtual proxy: applies to scenarios where small objects represent large objects in delayed initialization, reducing resource consumption and improving running speed.

  • You can use proxy mode when you do not want to change the original object but need to add additional functions such as permission control, logging, and flow control.

6. Responsibility chain mode

Definition:

The chain of responsibility pattern is a behavior design pattern that links the handlers of all requests into a chain by remembering the reference of the previous object to the next object. Once a request is received, each handler can either process it or pass it on to the next handler in the chain.

Responsibility chain pattern is a specific application of linked list structure in data structure.

Core ideas:

  • Abstract Handler: Defines an interface that contains processing methods and reference objects for the next node

  • ConcreteHandler: An implementation subclass of the abstract handler that determines whether this request is processed, handles it if necessary, or passes it on to the next node.

Advantages:

  • Reduces the degree of coupling between objects. Each node on the chain does its job, passing data through context, avoiding direct dependency.

  • Enhance system scalability. If there is a new business requirement, you only need to add a chain node at an appropriate location to meet the open and closed principle.

  • Flexible. If the business changes, the workflow needs to be adjusted, just need to dynamically adjust the order of the nodes on the chain. Even to meet the diverse needs of diversified businesses, we can define our own proprietary execution order for different business types.

  • Simplifies the connection between objects. Each object only needs to hold a reference to the next node, not all nodes.

  • Clear responsibilities. Each node only needs to handle its own work, and if it doesn’t, it passes it on to the next object. Define the scope of responsibility for each category, in line with the principle of single responsibility for each category.

This pattern is recommended for common gateway architectures like ours, where nodes can be freely added or removed anywhere through service choreography to meet a range of personalized functions.

Write in the last

A lot of people have learned design patterns, but they are always confused when they are working on projects, because they don’t understand what the core is, what the underlying logic is, as described in Design Patterns: Reusable Object-oriented Fundamentals.

Think about what should change in your design and encapsulate the concepts that will change.

The essence of software architecture is to find change and encapsulate it.

Business is changing, there is no fixed code answer, do not impose design patterns. Whichever design pattern you choose, try to meet SOLID principles and review yourself to see if it can meet the continuous scalability of the business. As the saying goes, “it doesn’t matter if a cat is black or white, it’s a good cat if it catches mice.”

More:

Github.com/aalansehaiy…

Author introduction: Tom brother, computer graduate student, the school recruited ali, P7 technical expert, has a patent, CSDN blog expert. Responsible for e-commerce transactions, community fresh, flow marketing, Internet finance and other businesses, many years of first-line team management experience