/
VendingMachineBetter.java
96 lines (77 loc) · 1.89 KB
/
VendingMachineBetter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.example.jingbin.designpattern.state.better;
import android.util.Log;
/**
* Created by jingbin on 2016/11/2.
* 自动售货机
*/
public class VendingMachineBetter {
private int count = 0;
private State currentState;
private State noMoneyState;
private State hasMoneyState;
private State soldState;
private State soldOutState;
private State winnerState;
public VendingMachineBetter(int count) {
noMoneyState = new NoMoneyState(this);
hasMoneyState = new HasMoneyState(this);
soldOutState = new SoldOutState(this);
soldState = new SoldState(this);
winnerState = new WinnerState(this);
if (count > 0) {
this.count = count;
currentState = noMoneyState;
}
}
/**
* 放钱
*/
public void insertMoney() {
currentState.insertMoney();
}
/**
* 退钱
*/
public void backMoney() {
currentState.backMoney();
}
/**
* 转动曲柄
*/
public void turnCrank() {
currentState.turnCrank();
if (currentState == soldState || currentState == winnerState) {
currentState.dispense();//两种情况会出货
}
}
/**
* 出商品
*/
public void dispense() {
Log.e("VendingMachineBetter", "---发出一件商品");
if (count > 0) {
count--;
}
}
public void setState(State state) {
this.currentState = state;
}
public State getNoMoneyState() {
return noMoneyState;
}
public State getHasMoneyState() {
return hasMoneyState;
}
public State getSoldState() {
return soldState;
}
public State getSoldOutState() {
return soldOutState;
}
public State getWinnerState() {
return winnerState;
}
public int getCount() {
return count;
}
}