和策略模式类似且不同;策略模式是切换不同的策略执行不同策略的统一方法;状态模式是切换不同的状态执行执行不同的方法;
执行的方法;
<pre>
public interface CarState {
void left();
void right();
void speedUp();
}
public class NoOilCarState implements CarState {
private static final String TAG = "NoOilCarState";
@Override
public void left() {
Log.i(TAG, "没油了");
}
@Override
public void right() {
Log.i(TAG, "没油了");
}
@Override
public void speedUp() {
Log.i(TAG, "没油了");
}
}
public class WithOilCarState implements CarState {
private static final String TAG = "WithOilCarState";
@Override
public void left() {
Log.i(TAG, "左转弯");
}
@Override
public void right() {
Log.i(TAG, "右转弯");
}
@Override
public void speedUp() {
Log.i(TAG, "加速");
}
</pre>
不同的状态
<pre>
public interface CarOilController {
public void withOil();
public void noOil();
}
public class Car implements CarOilController, CarState {
private static final String TAG = "Car";
@Override
public void withOil() {
setCarState(new WithOilCarState());
Log.i(TAG, "加油");
}
@Override
public void noOil() {
setCarState(new NoOilCarState());
Log.i(TAG, "没油");
}
private CarState carState = new NoOilCarState();//默认没油
private void setCarState(CarState carState) {
this.carState = carState;
}
@Override
public void left() {
carState.left();
}
@Override
public void right() {
carState.right();
}
@Override
public void speedUp() {
carState.speedUp();
}
}
</pre>
使用:
<pre>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Car car = new Car();
car.left();
car.right();
car.speedUp();
car.withOil();
car.left();
car.right();
car.speedUp();
car.noOil();
car.left();
car.right();
car.speedUp();
}
}
</pre>
log
<pre>
3-06 21:04:31.036 14663-14663/com.lerz.state I/NoOilCarState: 没油了
03-06 21:04:31.036 14663-14663/com.lerz.state I/NoOilCarState: 没油了
03-06 21:04:31.036 14663-14663/com.lerz.state I/NoOilCarState: 没油了
03-06 21:04:31.036 14663-14663/com.lerz.state I/Car: 加油
03-06 21:04:31.036 14663-14663/com.lerz.state I/WithOilCarState: 左转弯
03-06 21:04:31.036 14663-14663/com.lerz.state I/WithOilCarState: 右转弯
03-06 21:04:31.036 14663-14663/com.lerz.state I/WithOilCarState: 加速
03-06 21:04:31.036 14663-14663/com.lerz.state I/Car: 没油
03-06 21:04:31.036 14663-14663/com.lerz.state I/NoOilCarState: 没油了
03-06 21:04:31.036 14663-14663/com.lerz.state I/NoOilCarState: 没油了
03-06 21:04:31.036 14663-14663/com.lerz.state I/NoOilCarState: 没油了
</pre>
网友评论