在进行小规模开发时,直接通过声明某个类的实例,通过调用这个类的方法,以完成功能.
而在小规模开发转向大规模开发的时候,各种功能互相调用, 凌乱不堪.
此时, 通过将程序体分层, 规定某层的方法不能直接调用另外某些层的方法.这样能够显著减少程序体之间方法调用的复杂度, 更加有利于管理.
而命令模式,就是将调用类(Invoker)下发的命令(Command), 抽象成一个接口, 通过这个接口的实现类去调用被调用类(Receiver)的具体方法.
下图示: LogoutService.java需要调用UserDataManagement.java中的deleteUser()以及UserSessionManagement.java中的deleteSession()两个方法已达到注销当前用户的目的。
使用命令模式之后,将Command抽象成为一个接口userDao,LogoutService.java通过调用userDao的实现类,即可调用UserDataManagement.java中的deleteUser()以及UserSessionManagement.java中的deleteSession()两个方法。
包的结构
-LogoutService.java
package services;
import Dao.userDao;
import Dao.userDataDao;
import Dao.userSessionDao;
/**
* This is service which impl user to logout
* 1.delete from session
* 2.delete from database
* 3.return to login page
* Created by yl28537 on 6/09/2018.
*/
public class LogoutService {
private userDao userSessionDao = new userSessionDao();
private userDao userDataDao = new userDataDao();
public void logout(){
//1. delete from session
userSessionDao.delete();
//2. delete from database
userDataDao.delete();
//3. return to login page
System.out.println("return to login page");
}
}
- userDao.java
Command接口,拥有方法的声明。
package Dao;
/**
* Created by yl28537 on 6/09/2018.
*/
public interface userDao {
public void create();
public void delete();
}
- userDataDao.java
package Dao;
import utils.UserDataManagment;
/**
* Created by yl28537 on 6/09/2018.
*/
public class userDataDao implements userDao {
private UserDataManagment userDataManagment = new UserDataManagment();
@Override
public void create() {
userDataManagment.createUser();
}
@Override
public void delete() {
userDataManagment.deleteUser();
}
}
- userSessionDao.java
package Dao;
import utils.UserSessionManagment;
/**
* Created by yl28537 on 6/09/2018.
*/
public class userSessionDao implements userDao {
private UserSessionManagment userSessionManagment = new UserSessionManagment();
@Override
public void create() {
userSessionManagment.createSession();
}
@Override
public void delete() {
userSessionManagment.deleteSession();
}
}
- UserDataManagment.java
package utils;
/**
* This is a util class that will have all kinds of function to manage database
*/
public class UserDataManagment {
public void createUser(){
System.out.println("User created!");
}
public void deleteUser(){
System.out.println("User deleted!");
}
public void selectUser(){
System.out.println("User selected!");
}
}
- UserSessionManagement.java
package utils;
/**
* This is a util class that will have all kinds of method to manage session
*/
public class UserSessionManagment {
public void createSession(){
System.out.println("Session created!");
}
public void deleteSession(){
System.out.println("Session deleted!");
}
public void printSession(){
System.out.println("Print Session!");
}
}
宏命令
对于Command接口有多种实现。在Invoker中声明不同的command对象以达到宏命令的目的。
命令模式中的对象
1.请求者(Invoker):负责调用具体命令。一定会有至少一个Command接口的对象。
2.命令(Command):提供请求者需要的方法
3.具体命令(CommandImpl):通过调用接收者的方法,实现命令接口中的方法。
4.接受者(Receiver):命令的具体实现。