Have feelings, have dry goods, wechat search [three prince Aobin] concern about this programmer has a little bit of things.

This article has been included on GitHub github.com/JavaFamily.

Recently, a student asked me the difference between command mode, strategy mode and factory mode in an article about design patterns. Look at the code implementation does not feel any difference?

I’ve already shared with you the strategy mode and the factory mode and those of you who are interested can go over it again, but today we’re going to focus on the command mode and then we’re going to see what’s the difference between them?

Past reviews:

  • The singleton pattern
  • The factory pattern
  • The process engine
  • Builder mode
  • The prototype pattern
  • Chain of responsibility model
  • Observer mode
  • The strategy pattern
  • Template method
  • Iterator pattern
  • The proxy pattern
  • Object pool & interpreter pattern

Command mode

define
  • Provides a uniform way to encapsulate commands and determine which command action to choose to execute by parameter conditions.
  • Allows each command to be stored in a queue.

The overall structure is as follows:

Explanation of important roles in the structure diagram:

  • Command: An abstract wrapper class that defines a Command.
  • ConcreteCommand: an implementation of the Command class, specifically the actual implementation of the ConcreteCommand.
  • Receiver: The operation class associated with the command.
  • Invoker: The trigger command class, where an external action event triggers execution.
  • Client: Instantiates the specific command object, and the actual class of the recipient.

The whole structure actually seems to be relatively difficult to understand, but since I started learning design patterns, I must have an understanding of each design pattern to improve my knowledge

To further understand, let me give you an example that makes sense:

You must be familiar with the ancient Chinese monarchy. The emperor could instruct his father-in-law to receive or issue gifts. In fact, this is my personal feeling can reflect the command mode.

The father-in-law acts as the Receiver of the command mode, executing the orders of the emperor, receiving a ConcreteCommand or issuing a decree.

The emperor is the Invoker of command mode.

As usual, with the example done, let’s look at the code

Public interface Command {void execute(); } public class Receiver {public void Charge(){system.out.println (); } public void Issue(){system.out.println (" promulgation "); }} public class ConcreteCommandOne implements Command {public class ConcreteCommandOne implements Command {public class ConcreteCommandOne implements Command {public class ConcreteCommandOne implements Command {public class ConcreteCommandOne implements Command; public ConcreteCommandOne(Receiver receiver) { this.receiver = receiver; } @override public void execute() {// receiver.charge (); }} public class ConcreteCommandTwo implements Command {// Private Receiver Receiver;}} Public class ConcreteCommandTwo implements Command {// Private Receiver Receiver; public ConcreteCommandTwo(Receiver receiver) { this.receiver = receiver; } @override public void execute() {// Issue the message receiver.issue (); Public class Invoker {private Command Command; public Invoker(Command command) { this.command = command; } public void action() {command-execute (); }} demo public static void main(String[] args) {// instantiate a public Receiver Receiver Receiver =new Receiver(); CommandOne = new ConcreteCommandOne(receiver); // commandOne = new ConcreteCommandOne(receiver); Command commandTwo = new ConcreteCommandTwo(receiver); Invoker Invoker =new Invoker(commandOne); invoker.action(); // commandTwo =new Invoker(commandTwo); invokerTwo.action(); // result: a decree}Copy the code

This is a simple code implementation, with the Invoker (emperor) choosing to let the Receiver (father) decide what commands to execute. This is a simple manifestation of the command mode.

Those of you who are careful don’t know if you have found a problem in the definition

  • Allows each command to be stored in a queue.

We don’t have queues here, and it’s a very simple implementation. Just add a queue to the main method

Public static void main(String[] args) {// instantiate a public Receiver Receiver Receiver = new Receiver(); CommandOne = new ConcreteCommandOne(receiver); // commandOne = new ConcreteCommandOne(receiver); Command commandTwo = new ConcreteCommandTwo(receiver); Queue<Command> Queue = new LinkedList<>(); queue.add(commandOne); queue.add(commandTwo); For (Command Command: queue) {Invoker Invoker = new Invoker(Command); invoker.action(); }}Copy the code

So what I want to do here is to give you an extension point, and this is also one of the ways that I’ve seen check writing before.

Everyone in the real work will certainly encounter a lot of some of the interface check, how to write the check logic, how to do the code reuse, abstract and so on this is actually a more difficult problem!

Or roughly look at the structure diagram!!

I’ll write the demo code for you, but notice that we need to implement afterPropertiesSet in ApplicationContextAware.

Public abstract class ValidatePlugin {public abstract void validate(); } public abstract class ValidatePluginExecute {protected abstract List<ValidatePlugin> getValidatePlugins();  public void execute() { final List<ValidatePlugin> validatePlugins = getValidatePlugins(); if (CollectionUtils.isEmpty(validatePlugins)) { return; } for (ValidatePlugin ValidatePlugin: validatePlugins) {// Execute validateplugin.validate (); }}} @component ("validatePluginOne") public class validatePluginOne extends ValidatePlugin {@override public Void validate() {system.out.println ("validatePluginOne "); }} Add rule to validatePlugins @Component("testValidatePlugin") public Class testValidatePlugin extends ValidatePluginExecute implements ApplicationContextAware, InitializingBean { protected ApplicationContext applicationContext; private List<ValidatePlugin> validatePlugins; @override public void afterPropertiesSet() {// Add rule validatePlugins = Lists. NewArrayList (); validatePlugins.add((ValidatePlugin) this.applicationContext.getBean("validatePluginOne")); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override protected List<ValidatePlugin> getValidatePlugins() { return this.validatePlugins; }} demo public static void main(String[] args) {ApplicationContext ApplicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); TestValidatePlugin testValidatePlugin = (TestValidatePlugin) applicationContext.getBean("testValidatePlugin"); testValidatePlugin.execute(); }Copy the code

This is just a simple test demo, just to give you something to think about, design patterns don’t have to copy code. More is to expand their vision, improve their ability to solve problems.

For different interfaces, we only need to add specific validation rules in TestValidatePlugin, and the overall scalability is high, and it looks very high.

So what is the difference between command mode, policy mode, and factory mode?

  • Command mode: it belongs to the behavioral design mode. In command mode, different commands will produce different results during execution, and different commands cannot be replaced.
  • Policy pattern: a behavioral design pattern. In policy pattern, the focus is on the execution of each policy, solving the problem of choosing different policies from a set of policies based on the runtime state
  • Factory pattern: A creative design pattern, in which the focus is on encapsulating the creation of objects that are not defined by any business scenario and can be policies, but can also be something else

Therefore, in terms of design patterns, actually I understand only one problem. Different design patterns are designed to deal with different scenarios, and different business scenarios have different writing methods.

The mediator model

The intermediary model, as the name suggests, has an intermediate structure to facilitate the management of downstream organizations.

So what is the mediation model?

As explained in Design Patterns in GoF, a mediation pattern defines a single (mediation) object that encapsulates the interaction between a set of objects. Delegate the interaction between this set of objects to the mediation object interaction to avoid direct interaction between objects.

Take a look at the structure:

  • Mediator: Used to define how actors and intermediaries interact

  • ConcreteMediator: Implements the operation defined by the mediator, that is, implements the interaction.

  • Colleague: An abstract class or interface that defines how actors interact.

  • ConcreteColleague: A simple, concrete implementation of the Colleague method.

    The above structural definitions come from the beauty of design patterns

If you look at this diagram, it’s actually a little bit similar to the observer pattern that I wrote for you before, so if you’re interested in it, you can review it.

Old rules, or specific examples of code implementation

In the HSR system you should know that there is a dispatch center that controls the order of arrival of each HSR train. If you don’t have this dispatch center, when there are three HSR trains coming into the station at the same time, they need to communicate in pairs. If one of the bullet trains fails to communicate, an immeasurable error will occur, so it is necessary to handle the communication logic through the dispatch center and manage how many vehicles are waiting to arrive at the station.

Public interface Colleague {public interface Colleague {void message(); } public interface Mediator {void doEvent(Colleague);} public interface Mediator {void doEvent(Colleague); } @Component public class MotorCarOneColleague implements Colleague {@override public void message() {// System.out.println(" HSR 1 received message!! ") ); } } @Component public class MotorCarTwoColleague implements Colleague { @Override public void message() { System.out.println(" HSR 2 received message!! ") ); } } @Component public class MotorCarThreeColleague implements Colleague { @Override public void message() { System.out.println(" HSR 3 received message!! ") ); }} @component public class DispatchCenter implements Mediator {// Manage @autowired private List<Colleague>  colleagues; @Override public void doEvent(Colleague colleague) { for(Colleague colleague1 :colleagues){ if(colleague1==colleague){ // doSomeThing(); // doSomeThing(); continue; } // Notify other participants colleague1.message(); Public static void main(String[] args) {// Initialize spring container ApplicationContext ApplicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); / / get broker, dispatching center DispatchCenter DispatchCenter = (DispatchCenter) applicationContext. GetBean (" DispatchCenter "); MotorCarOneColleague MotorCarOneColleague = (MotorCarOneColleague) applicationContext.getBean("motorCarOneColleague"); // communicate information via dispatchCenter dispatchcenter.doevent (motorCarOneColleague); // result: high speed rail 3 received the message!! // High-speed Rail 2 received message!! // No. 2 high-speed train sends out the message (MotorCarTwoColleague)applicationContext.getBean("motorCarTwoColleague"); dispatchCenter.doEvent(motorCarTwoColleague); // result: high-speed train 1 received message!! // High Speed Rail 3 received the message!! }Copy the code

So we’re done with the broker demo code, and you should see from this demo that the broker is pretty easy to understand.

However, the application scenario of intermediaries is still relatively rare. For some similar network structure formed by serious class dependence, change it to a structure similar to dandelion and spread out from the middle to achieve the effect of decoupling.

This is more common in a UI control, but in Java java.util.Timer can also be thought of as a mediator mode because it controls how the internal thread runs, such as how often.

The mediator and observer patterns mentioned above are very similar, as you can see from the demo code

In the observer model, the observer and the observed are basically fixed, whereas in the mediator model, the observer and the observed are not fixed, and the mediator may end up as a large primitive class.

conclusion

Command mode: It’s not very common, but it’s important to distinguish what it is from factory mode and strategy mode, what the application scenarios are, and what it gives us to think about.

For example, in my last example, the command pattern implements the storage of commands, essentially maintaining commands in a queue, so why can’t we also maintain some interface validation dependencies in our business code through an array that holds the bean instances that need to be validated? To improve code reusability and extensibility.

Mediation patterns: the more less application as a whole, although can play object, decoupling, but also have side effects, but also in the real business scenarios we rarely encountered such scene, understand the implementation principle, and as for the difference between the observer and has talked about above, we may have more in the use of some message queue middleware to deal with.

I’m Aobin, the more you know, the more you don’t know, thanks for your likes, favorites and comments, we’ll see you next time!


The article continues to update, can wechat search a search “three prince Aobin” the first time to read, reply [data] I prepared for the first line of dafang interview data and resume template, this article GitHub github.com/JavaFamily has been included, there are dafang interview complete test point, welcome to Star.