㈠:State模式屬於對象形爲型設計模式;它是將對象在不一樣狀態下所表現出的行爲進行抽象成類;意圖是:容許當類的狀態改變時改變與之對應的行爲;設計模式
㈡:類圖app
㈢:場景描述ide
最近歐洲盃如火如荼地進行啊,要論焦點人物,固然是巴神莫屬啊.如今咱們就以他爲例來Mapping一下State設計模式吧.測試
巴神神的時候,能夠打進驚世倒鉤;this
巴神Crazy的時候,會思考下人生;spa
正常的巴神;你永遠不懂啊;設計
這不正是巴神在不一樣的狀態下所表現出的不一樣的行爲嗎?orm
歐洲盃正是巴神所處的Context啊.對象
抽象之: get
- /**
- * State下共同的行爲抽象
- */
- package com.skywares.designpattern.state.abstractState;
- /**
- * @author hubert
- *
- */
- public interface BalotelliPlay {
- public void play();
- }
- package com.skywares.designpattern.state.concretestate;
- import com.skywares.designpattern.state.abstractState.BalotelliPlay;
- /**
- * 神同樣的巴神
- * @author hubert
- *
- */
- public class BalotelliGodPlay implements BalotelliPlay {
- @Override
- public void play() {
- System.out.println(" 打進一個倒鉤 ...... ");
- }
- }
- /**
- * 瘋子(呵呵)
- */
- package com.skywares.designpattern.state.concretestate;
- import com.skywares.designpattern.state.abstractState.BalotelliPlay;
- /**
- * @author hubert
- *
- */
- public class BalotelliCrazyPlay implements BalotelliPlay{
- @Override
- public void play() {
- System.out.println(" 單刀了, so easy,思考下人生!! ");
- }
- }
- /**
- * 正常的巴神
- */
- package com.skywares.designpattern.state.concretestate;
- import com.skywares.designpattern.state.abstractState.BalotelliPlay;
- /**
- * @author hubert
- *
- */
- public class BalotelliNormalPlay implements BalotelliPlay {
- @Override
- public void play() {
- System.out.println("巴神的世界你永遠不懂得 ..");
- }
- }
歐洲盃登場:看巴神表現:
測試類:
- /**
- * Context;
- */
- package com.skywares.designpattern.state.context;
- import com.skywares.designpattern.state.abstractState.BalotelliPlay;
- import com.skywares.designpattern.state.concretestate.BalotelliCrazyPlay;
- import com.skywares.designpattern.state.concretestate.BalotelliGodPlay;
- import com.skywares.designpattern.state.concretestate.BalotelliNormalPlay;
- /**
- * @author hubert
- *
- */
- public class EuropeCupContext {
- private BalotelliPlay balotelliPlay = new BalotelliNormalPlay();
- private int competitionSession = 1;
- public int getCompetitionSession() {
- return competitionSession;
- }
- public void setCompetitionSession(int competitionSession) {
- this.competitionSession = competitionSession;
- }
- public void changeSession()
- {
- switch(competitionSession)
- {
- case 1:
- balotelliPlay = new BalotelliCrazyPlay();
- break;
- case 2:
- balotelliPlay = new BalotelliGodPlay();
- break;
- default:
- ;
- }
- }
- public void balotelliPlayInMatch()
- {
- balotelliPlay.play();
- }
- }
- package com.skywares.designpattern.state.context;
- /**
- * @author hubert
- *
- */
- public class TestState {
- /**
- * @param args
- */
- public static void main(String[] args) {
- EuropeCupContext context = new EuropeCupContext();
- context.balotelliPlayInMatch();
- context.setCompetitionSession(1);
- context.changeSession();
- context.balotelliPlayInMatch();
- context.setCompetitionSession(2);
- context.changeSession();
- context.balotelliPlayInMatch();
- }
- }