程序员蜗牛
1 year ago
3 changed files with 73 additions and 0 deletions
@ -0,0 +1,18 @@ |
|||
package com.woniu.mp.zhuangtai; |
|||
|
|||
import lombok.Data; |
|||
|
|||
|
|||
@Data |
|||
public class Order { |
|||
|
|||
private OrderStateEnum state; |
|||
|
|||
public Order() { |
|||
state = OrderStateEnum.UNPAY; |
|||
} |
|||
|
|||
public void nextState(){ |
|||
state.nextState(this); |
|||
} |
|||
} |
@ -0,0 +1,35 @@ |
|||
package com.woniu.mp.zhuangtai; |
|||
|
|||
/** |
|||
* @className: OrderStateEnum |
|||
* @author: woniu |
|||
* @date: 2023/12/2 |
|||
**/ |
|||
public enum OrderStateEnum { |
|||
|
|||
//未支付
|
|||
UNPAY { |
|||
@Override |
|||
public void nextState(Order order) { |
|||
order.setState(PAID); |
|||
} |
|||
}, //已支付
|
|||
PAID { |
|||
@Override |
|||
public void nextState(Order order) { |
|||
order.setState(FINISHED); |
|||
} |
|||
}, |
|||
|
|||
FINISHED { |
|||
@Override |
|||
public void nextState(Order order) { |
|||
order.setState(PAID); |
|||
} |
|||
}; |
|||
|
|||
|
|||
public abstract void nextState(Order order); |
|||
|
|||
|
|||
} |
@ -0,0 +1,20 @@ |
|||
package com.woniu.mp.zhuangtai; |
|||
|
|||
|
|||
/** |
|||
* 使用状态模式优化代码 解决代码中的if else |
|||
*/ |
|||
public class TestMain { |
|||
// Order 未支付-> 已支付-> 已完成
|
|||
public static void main(String[] args) { |
|||
Order order = new Order(); |
|||
// if (order.getState() == "") {
|
|||
// order.setState(OrderStateEnum.PAID);
|
|||
// }
|
|||
System.out.println(order.getState()); |
|||
order.nextState(); |
|||
System.out.println(order.getState()); |
|||
order.nextState(); |
|||
System.out.println(order.getState()); |
|||
} |
|||
} |
Loading…
Reference in new issue