One 、 What is an order (Command) Pattern

Command pattern is a kind of behavioral design pattern , The purpose is to encapsulate a request as an object , This allows you to parameterize clients with different requests . Compared to another way of combining each command with the object calling the command to form a proprietary class , The advantage of command mode is that it decouples the object that calls the operation from the object that knows how to implement it , Adding new commands does not require modifying existing classes .

The structure of the command mode is as follows :

The participants are :

1.Invoker Requestor

Ask the command to execute the request , The caller of the command

2.Command Interface

3.ConcreteCommand Specific interface

4.Receiver The receiver

The actual implementer of the related operation of the command


Collaborative process :

1.Client Create a ConcreteCommand Object and specify its Receiver object

2. some Invoker Object to store the ConcreteCommand object

3. The Invoker By calling Command Object's Excute Operation to submit a request . If the command is revocable ,ConcreteCommand Right now Excute The current state is stored before the operation to cancel the command

4.ConcreteCommand Object to call its Receiver To perform the request

Two 、go-redis command Related codes

// commands.go
// Invoker Requester interface 
type Cmdable interface {
Pipeline() Pipeliner
Pipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error)
TxPipelined(ctx context.Context, fn func(Pipeliner) error) ([]Cmder, error)
TxPipeline() Pipeliner
Command(ctx context.Context) *CommandsInfoCmd
ClientGetName(ctx context.Context) *StringCmd
// ...
// And all Redis Command related methods
} // cmdable Realized Cmdable Interface
type cmdable func(ctx context.Context, cmd Cmder) error
func (c cmdable) Echo(ctx context.Context, message interface{}) *StringCmd {
cmd := NewStringCmd(ctx, "echo", message)
_ = c(ctx, cmd)
return cmd

It's worth mentioning here cmdable Is a function type ,func(ctx context.Context, cmd Cmder) error

And each cmdable There will be in every way _ = c(ctx, cmd), That is how to call cmd It's not clearly written here

Look back again redis.go, You'll find this piece of code

type Client struct {
ctx context.Context
} func NewClient(opt *Options) *Client {
opt.init() c := Client{
baseClient: newBaseClient(opt, newConnPool(opt)),
ctx: context.Background(),
c.cmdable = c.Process // Underline return &c

c.cmdable = c.Process This line specifies how the request calls Command Of

stay ctrl+ Left click to track several layers , Will be in redis.go Find the specific procedure of the call in

// redis.go
func (c *baseClient) process(ctx context.Context, cmd Cmder) error {
err := cn.WithWriter(ctx, c.opt.WriteTimeout, func(wr *proto.Writer) error {
eturn writeCmd(wr, cmd)
}) err = cn.WithReader(ctx, c.cmdTimeout(cmd), cmd.readReply)

Then look for it Command, This is clearer , All in command.go in

// command.go
// Command Interface 
type Cmder interface {
Name() string
FullName() string
Args() []interface{}
String() string
stringArg(int) string
firstKeyPos() int8
setFirstKeyPos(int8) readTimeout() *time.Duration
readReply(rd *proto.Reader) error SetErr(error)
Err() error
} // Many more Cmder The concrete realization of , Part of the code for one of the implementations is as follows
type XPendingExtCmd struct {
val []XPendingExt
func (cmd *XPendingExtCmd) Val() []XPendingExt {
return cmd.val

I don't see it here Receiver, It's because of each Cmder All the functions are realized by themselves , There is no need for additional recipient objects .

3、 ... and 、 summary

Sometimes you have to submit a request to an object , But you don't know anything about the requested operation or the recipient of the request . You can use command mode at this time , By turning the request itself into an object, toolbox objects can make requests to unspecified application objects .

Command mode and go-redis command More articles on Design

  1. c# Design pattern series : Command mode (Command Pattern)

    introduction Command mode , I feel " command " It's the task , The execution of the command completes a task . Or say , Orders are tasks , From this name, we don't know who the sender and receiver of the order are , Why? ? Because we don't care who they are , ...

  2. Design patterns --- Command mode of behavior change mode (Command)

    Premise : Behavioral change patterns In the process of building components , Changes in build behavior often lead to drastic changes in the component itself .“ Behavior change ” Patterns decouple the behavior of a component from the component itself , To support component changes , Achieve loose coupling between the two . Class and static function methods ...

  3. Command mode (head first Design patterns 5)

    One . Command mode definition Orders are familiar to all , So before you start command mode , Imagine the characteristics of command mode in life : If the boss orders you to complete a OA Project is a command , And then look at the characteristics : 1. In the above order , The executor of the order must be smart ...

  4. C# Design pattern learning notes :(14) Command mode

    This note is taken from :, Record the learning process for future reference . One . introduction Today we are going to talk about the second pattern of behavioral design pattern -- life ...

  5. OOP Design patterns [JAVA]——04 Command mode

    Command mode The intent of command mode Command mode belongs to the behavior mode of the object . Another name is :Action or Transaction. Command mode encapsulates a request or operation into an object . Command mode allows the system to parameterize the client with different requests , Request for ...

  6. Design patterns ( 6、 ... and ): In the console “ Command mode ”(Command Pattern)

    In today's blog, I'll sort it out systematically “ Command mode ”. When it comes to command mode , I think of the console (Console) The command . Whether it's Windows operating system (cmd.exe) still Linux operating system ( Command line shell(Comm ...

  7. ( 13、 ... and )WebGIS The command mode of toolbar design in

    The copyright of the article is jointly owned by Li Xiaohui and blog park , If reprint, please indicate the source clearly : 1. background Starting from this chapter, we will officially enter WebGIS Related functions in the toolbar of ...

  8. C++ Design patterns -Command Command mode

    Command Command mode functions : Encapsulate a request as an object , This allows you to parameterize customers with different requests : Queues or logs requests , And support for undo operations . because “ Action requester ” And “ The implementer of the act ” The tight coupling of , Use command mode ...

  9. Simple design patterns —— Command mode (Command Pattern)

    Pattern motivation In software design , We often need to send requests to certain objects , But I don't know who the recipient of the request is , I don't know what the requested operation is , We just need to specify the specific request receiver when the program is running , here , You can use command mode to design , Please ...

  10. C# Design patterns (15)—— Command mode (Command Pattern)

    One . Preface I've been busy with my work before , The design pattern series has not been updated , Recent projects have found that , An understanding of design patterns is essential , Of course, it's more important for the application of design patterns , It can be said that whether you know how to apply design patterns is a measure of a programmer in a project ...

Random recommendation

  1. Mac To configure php-fpm When '/private/etc/php-fpm.conf': No such file or directory (2) Mac Bring their own php-fpm, Execute at the terminal  php-fpm, The following errors will be reported : ERROR: failed to open ...

  2. actual combat MEF(3): Export only members of the class

    Through the introduction of the previous two articles , I believe you will understand MEF There is a lot of practical value in it . We also discussed import and export in the previous article , For export import , Today, let's go a little deeper , Um. , It's just a little deeper , It won't be hard , Please don't worry about big housework , If you feel like reading the article ...

  3. [C#6] 2-nameof Operator

    0. Catalog C#6 New feature catalog 1. Older code using System; namespace csharp6 { internal class Program { private static ...

  4. 【 turn 】IPtables Learning notes

    Write it at the front , Let's test and play iptables Remember to configure those things when you do , Remember to delete after the test , The blogger forgot to delete one input REJECT A record of the chain , Follow up tests set up apache The server , Always inaccessible , Finally, we found that ...

  5. js Local parsing xls file

    There's a plug-in here take demo Copy and organize ( Be careful js Complete ) that will do . Here to download :

  6. 【Android Multi screen adaptation 】 The dynamic change Listview item Height

    stay ListView Of Adapter To get the input directly View Of LayoutParams It will report null pointer exception , The only way is in xml Nested layout in a layer LinearLayout <?xml version=& ...

  7. LINK : fatal error LNK1181: Can't open input file “..\..\lib\Release\opencv_ocl249.lib”

    What do you want to compile recently OpenCV resources . View source code debugging execution . According to the article on the Internet <Win7x64+VS2012+OpenCV2.4.3+CMake2.8.10+TBB41 Recompile OpenCV>  Match ...

  8. Nginx and IIS To achieve dynamic and static separation 【 Reprint 】

    Some time ago , To make Nginx+IIS Load balancing of , Friends who want to know , You can read this article :<nginx and IIS Load balancing >, And then I studied it by the way Nginx + IIS To achieve dynamic and static separation . therefore , Let's sum it up ...

  9. MongoDB Introductory series ( 3、 ... and ): Inquire about (SELECT)

    One . summary mongodb It's closest to a relational database NOSQL database , It's very flexible to store : So much so that you think of it as a redundant table in a relational database , This is also Mongodb A feature of atomicity . Because there is no relational database ...

  10. PAT L3-020 Delete at most three characters Given a string of all lowercase letters , allow ...