State狀態設計模式類似於Switch多路分支功能的開關,State狀態模式機制如下:
狀態模式UML圖如下:
State狀態設計模式用於改變對象的行爲,在代理的生命週期裏,隨着狀態變化從一個目標實現程序切換到另一個目標實現程序。
我們經常遇到如下的程序代碼:
- public class Creature{
- private Boolean isFrog = true;//標識
- public void greet(){
- if(isForg){
- System.out.println(“Ribbet!”);
- }else{
- System.out.println(“Darling!”);
- }
- }
- //轉換標識
- public void kiss(){
- isForg = false;
- }
- public static void main(String[] args){
- Creature creature = new Creature();
- creature.greet();
- creature.kiss();
- creature.greet();
- }
- }
- public class Creature{
- //狀態接口
- private interface State{
- String response();
- }
- private class Forg implements State{
- public String response(){
- return “Ribbet!”;
- }
- }
- private class Prince implements State{
- public String response(){
- return “Darling!”;
- }
- }
- private State state = new Forg();
- public void greet(){
- System.out.println(state.response);
- }
- public void kiss(){
- state = new Prince();
- }
- public static void main(String[] args){
- Creature creature = new Creature();
- creature.greet();
- creature.kiss();
- creature.greet();
- }
- }
State狀態設計模式中,狀態自動切換並傳播,不需要再改動標識,代碼顯得非常優雅。
State狀態設計模式一個基本框架如下:
- //狀態接口
- interface State{
- void operation1();
- void operation2();
- void operation3();
- }
- //狀態實現類1
- class implementation1 implements State{
- public void operation1(){
- System.out.println(“Implementation1.operation1()”);
- }
- public void operation2(){
- System.out.println(“Implementation1.operation2()”);
- }
- public void operation3(){
- System.out.println(“Implementation1.operation3()”);
- }
- }
- //狀態實現類2
- class implementation2 implements State{
- public void operation1(){
- System.out.println(“Implementation2.operation1()”);
- }
- public void operation2(){
- System.out.println(“Implementation2.operation2()”);
- }
- public void operation3(){
- System.out.println(“Implementation2.operation3()”);
- }
- }
- //服務提供者
- class ServiceProvider{
- private State state;
- public ServiceProvider(State state){
- this.state = state;
- }
- //狀態更改
- public void changeState(State newState){
- state = newState;
- }
- public void service1(){
- //……
- state.operation1();
- //……
- state.operation3();
- }
- public void service2(){
- //……
- state.operation1();
- //……
- state.operation2();
- }
- public void service3(){
- //……
- state.operation3();
- //……
- state.operation2();
- }
- }
- public class StateDemo{
- private ServiceProvider sp = new ServiceProvider(new Implementation1());
- private void run(ServiceProvider sp){
- sp.service1();
- sp.service2();
- sp.service3();
- }
- public static void main(String[] args){
- StateDemo demo = new StateDemo();
- demo.run(sp);
- sp.changeState(new Implementation2());
- demo.run(sp);
- }
- }
State狀態模式和Proxy代理模式都爲客戶端程序提供了一個目標程序代理,真正的目標程序被代理所隱藏,當客戶端程序調用目標程序時,首先將調用請求發送給代理,代理才真正調用目標程序,但是Proxy代理模式和State狀態模式有如下區別:
(1).Proxy代理模式中被調用的目標程序只有一個,而State狀態模式中被調用的目標程序有多個。
(2).Proxy代理模式的目的是控制客戶端對目標程序的訪問,而State狀態模式是爲了根據條件動態改變目標程序。
轉自:點擊打開鏈接