一文带你详细了解命令模式及实例解析

·  阅读 184

1.简介

The command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.

(命令模式是一种行为设计模式,其中一个对象用于封装所有信息,以便在以后执行某个操作或触发某个事件。此信息包括方法名称、拥有方法的对象和方法参数的值)

—— quote from Wikipedia

	简而言之,命令模式就是将封装了相关方法的类进行收集并调用,最终实现相应的结果。
复制代码

2.命令模式的优缺点:

优点:

1、降低了系统耦合度。

2、新的命令可以很容易添加到系统中去。

缺点:

使用命令模式可能会导致某些系统有过多的具体命令类。

3.相关实例解析

  		举个常见的例子,小明去上海旅游,有出发和返程的方法。然后代理类放入相关的类,将其正确的执行。
复制代码

相关代码:

// 旅游接口
interface Place {
    void travel();
}

class Person {

    private String name = "xiaoming";
    private int age = 18;

    // 出发
    public void setOff() {
        System.out.println("name:[" + name + "] " + "age:[" + age + "] " + "set off");

    }

    // 返程
    public void getBack() {
        System.out.println("name:[" + name + "] " + "age:[" + age + "] " + "get back");
    }
}


// 上海旅游
class GoToShangHai implements Place {

    private Person person;

    public GoToShangHai(Person person) {
        this.person = person;
    }

    @Override
    public void travel() {
        person.setOff();
        System.out.println("tarvel around ShangHai");
    }
}

// 从上海返程
class BackFromShangHai implements Place {

    private Person person;

    public BackFromShangHai(Person person) {
        this.person = person;
    }

    @Override
    public void travel() {
        person.getBack();
        System.out.println("get back from ShangHai");
    }
}

class  Proxy{
    private List<Place> placeList = new ArrayList<>();

    public void travelPlace(Place place) {
        placeList.add(place);
    }

    public void places() {
        for (Place place : placeList) {
            place.travel();
        }
        placeList.clear();
    }

}


public class CommondDemo {

    public static void main(String[] args) {
        Person person = new Person();
        GoToShangHai goToShangHai = new GoToShangHai(person);
        BackFromShangHai backFromShangHai = new BackFromShangHai(person);

        Proxy proxy = new Proxy();
        proxy.travelPlace(goToShangHai);
        proxy.travelPlace(backFromShangHai);

        proxy.places();
    }
}
复制代码
输出结果:
name:[xiaoming] age:[18] set off
tarvel around ShangHai
name:[xiaoming] age:[18] get back
get back from ShangHai
复制代码

分类:
后端
标签:
分类:
后端
标签: