״̬ģʽ-State Pattern(JavaʵÏÖ)

2018-06-18 00:54:11À´Ô´£ºÎ´Öª ÔĶÁ ()

ÐÂÀÏ¿Í»§´ó»ØÀ¡,ÔÆ·þÎñÆ÷µÍÖÁ5ÕÛ

״̬ģʽ-State Pattern

ÔÚ״̬ģʽ(State Pattern)ÖÐ,ÀàµÄÐÐΪÊÇ»ùÓÚËüµÄ״̬¸Ä±äµÄ¡£µ±Ò»¸ö¶ÔÏóµÄÄÚÔÚ״̬¸Ä±äʱÔÊÐí¸Ä±äÆäÐÐΪ£¬Õâ¸ö¶ÔÏó¿´ÆðÀ´ÏñÊǸıäÁËÆäÀà¡£

State½Ó¿Ú

±íÃ÷״̬, ʵÌåÀàÊǸù¾Ý״̬µÄ±ä»¯¶ø·¢ÉúÏìÓ¦ÐÐΪµÄ±ä»¯µÄ.

/**
 * ״̬³éÏó¶¨Òå
 */
public interface State {

    void onEnterState();

    void observe();

}

AngryStateÀà

״̬µÄÒ»ÖÖʵÏÖ.

/**
 * ÉúÆø״̬
 */
public class AngryState implements State {

    private Mammoth mammoth;

    public AngryState(Mammoth mammoth) {
        this.mammoth = mammoth;
    }

    @Override
    public void observe() {
        System.out.printf("%s ´¦ÓÚ±©Ôê״̬!\n", mammoth);
    }

    @Override
    public void onEnterState() {
        System.out.printf("%s ¿ªÊ¼ÉúÆøÁË!\n", mammoth);
    }
}

PeacefulStateÀà

״̬µÄÒ»ÖÖʵÏÖ.

/**
 * ƽ¾²×´Ì¬
 */
public class PeacefulState implements State {

    private Mammoth mammoth;

    public PeacefulState(Mammoth mammoth) {
        this.mammoth = mammoth;
    }

    @Override
    public void observe() {
        System.out.printf("%s ÏÖÔÚºÜƽ¾².\n", mammoth);
    }

    @Override
    public void onEnterState() {
        System.out.printf("%s ¿ªÊ¼Àä¾²ÏÂÀ´ÁË.\n", mammoth);
    }
}

MammothÀà

±¾ÀàÊÇ״̬StateµÄ³ÖÓÐÕß

/**
 * ÃÍáï´óÏó
 */
public class Mammoth {

    private State state;

    public Mammoth() {
        state = new PeacefulState(this);
    }

    public void timePasses() {
        if (state.getClass().equals(PeacefulState.class)) {
            changeStateTo(new AngryState(this));
        } else {
            changeStateTo(new PeacefulState(this));
        }
    }

    private void changeStateTo(State newState) {
        this.state = newState;
        this.state.onEnterState();
    }

    public void observe() {
        this.state.observe();
    }

    @Override
    public String toString() {
        return "ÃÍáï´óÏó";
    }
}

Main

ÓÃÓÚÄ£Äⳡ¾°ÒÔ¼°ÔËÐдúÂë

public class Main {

    public static void main(String[] args) {

        Mammoth mammoth = new Mammoth();
        // ¿´¿´´óÏóÏÖÔÚÊÇʲô״̬
        mammoth.observe();

        // ¹ýÁËÒ»»á¶ù
        mammoth.timePasses();

        // ¿´¿´´óÏóÏÖÔÚÊÇʲô״̬
        mammoth.observe();

        // ¹ýÁËÒ»»á¶ù
        mammoth.timePasses();

        // ¿´¿´´óÏóÏÖÔÚÊÇʲô״̬
        mammoth.observe();

    }
}

 ÔËÐнá¹ûÈçÏÂ:

±êÇ©£º

°æȨÉêÃ÷£º±¾Õ¾ÎÄÕ²¿·Ö×ÔÍøÂ磬ÈçÓÐÇÖȨ£¬ÇëÁªÏµ£ºwest999com@outlook.com
Ìرð×¢Ò⣺±¾Õ¾ËùÓÐתÔØÎÄÕÂÑÔÂÛ²»´ú±í±¾Õ¾¹Ûµã£¬±¾Õ¾ËùÌṩµÄÉãÓ°ÕÕƬ£¬²å»­£¬Éè¼Æ×÷Æ·£¬ÈçÐèʹÓã¬ÇëÓëÔ­×÷ÕßÁªÏµ£¬°æȨ¹éÔ­×÷ÕßËùÓÐ

ÉÏһƪ£ºAndroid Studio 3.1.2 Device File Explorer nothing to show

ÏÂһƪ£ºIntelliJ IDEAÔ¶³Ìµ÷ÊÔÔËÐÐÖеÄJAVA³ÌÐò/ÏîÄ¿