feat: 新增默认方法、调整方法名及文档注释.

This commit is contained in:
2025-04-23 17:19:58 +08:00
parent e2a58cf7bd
commit cd24c7de99
2 changed files with 27 additions and 5 deletions

View File

@@ -58,7 +58,7 @@ public interface StateManager<S> {
* @param state 指定的状态
* @return 符合返回真, 否则返回假
*/
default boolean now(S state) {
default boolean is(S state) {
return current().equals(state);
}
@@ -71,9 +71,20 @@ public interface StateManager<S> {
* @param newState 新的状态
* @return 如果当前状态不符合或者不可切换则返回假, 否则走切换逻辑, 此时结果取决于切换的结果.
*/
default boolean switchToIfPresent(S now, S newState) {
default boolean switchToIfMatch(S now, S newState) {
if (isSwitchable() || now.equals(current()))
return switchTo(newState);
return false;
}
/**
* 如果当前状态为指定的状态则运行所指定的逻辑
*
* @param state 状态
* @param action 逻辑
*/
default void computeIfMatch(S state, Runnable action) {
if (is(state))
action.run();
}
}

View File

@@ -1,8 +1,6 @@
package com.serliunx.statemanagement;
import com.serliunx.statemanagement.manager.BreakageUnidirectionalStateManager;
import com.serliunx.statemanagement.manager.DefaultUnidirectionalStateManager;
import com.serliunx.statemanagement.manager.UnidirectionalStateManager;
import com.serliunx.statemanagement.manager.*;
import com.serliunx.statemanagement.support.PrinterState;
import org.junit.Test;
import org.slf4j.Logger;
@@ -37,4 +35,17 @@ public class ManagerTest {
}
System.out.println(bum.current());
}
@Test
public void testDefaultMethod() throws Exception {
BidirectionalStateManager<PrinterState> bsm = new DefaultBidirectionalStateManager<>(PrinterState.values());
bsm.switchPrev();
log.info("{}", bsm.current());
bsm.computeIfMatch(PrinterState.IDLE, () -> {
log.info("hello~");
});
}
}