设计模式(Design Pattern) - 行为型模式(Behavioral Pattern) - 命令模式(Command) - Java实现

设计模式(Design Pattern) - 行为型模式(Behavioral Pattern) - 命令模式(Command)
目的:达到命令的发出者和执行者之间解耦,实现请求和执行分开。

一、说明:
1、Command 命令(接口);
2、Receiver 命令接收者;
3、MyCommand 命令.实现类;
4、Invoker 命令发送者。

二、Java实现,代码如下:
1、Command

package com.java.designPattern.command;

/**
 * 命令 - 接口
 *
 */
public interface Command {

    /**
     * 执行命令
     */
    public void exe();

}

2、Receiver

package com.java.designPattern.command;

/**
 * 命令接收者
 *
 */
public class Receiver {

    public void action() {
        System.out.println("command receive!");
    }

}

3、MyCommand

package com.java.designPattern.command;

public class MyCommand implements Command {

    private Receiver receiver;

    public MyCommand(Receiver receiver) {
        this.receiver = receiver;
    }

    @Override
    public void exe() {
        receiver.action();
    }

}

4、Invoker

package com.java.designPattern.command;

/**
 * 命令发送者
 *
 */
public class Invoker {

    private Command command;

    public Invoker(Command command) {
        this.command = command;
    }

    public void action() {
        this.command.exe();
    }

}

5、Test

package com.java.designPattern.command;

public class Test {

    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        Command command = new MyCommand(receiver);
        Invoker invoker = new Invoker(command);
        invoker.action();
    }

}

输出:
command receive!

你可能感兴趣的:(设计模式,行为型模式)