关闭

java设计模式进阶_state

标签: java设计模式
1331人阅读 评论(0) 收藏 举报
分类:

这里写图片描述

//
//
//  Generated by StarUML(tm) Java Add-In
//
//  @ Project : Untitled
//  @ File Name : State.java
//  @ Date : 2016/8/30
//  @ Author : 
//
//




public interface State {
    public void onEnterState();
    public void observe();
}

//
//
//  Generated by StarUML(tm) Java Add-In
//
//  @ Project : Untitled
//  @ File Name : PeacefulState.java
//  @ Date : 2016/8/30
//  @ Author : 
//
//




public class PeacefulState implements State {

    private Mammoth mammoth;

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

    public void onEnterState() {
        System.out.println(String.format("%s calms down.", mammoth));
    }

    public void observe() {
        System.out.println(String.format("%s is calm and peaceful.", mammoth));
    }
}

//
//
//  Generated by StarUML(tm) Java Add-In
//
//  @ Project : Untitled
//  @ File Name : AngryState.java
//  @ Date : 2016/8/30
//  @ Author : 
//
//




public class AngryState implements State {

    private Mammoth mammoth;

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

    public void onEnterState() {
        System.out.println(String.format("%s gets angry!", mammoth));
    }

    public void observe() {
        System.out.println(String.format("%s is furious!", mammoth));
    }
}


//
//
//  Generated by StarUML(tm) Java Add-In
//
//  @ Project : Untitled
//  @ File Name : Mammoth.java
//  @ Date : 2016/8/30
//  @ Author : 
//
//




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 String toString() {
        return "The mammoth";
    }

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


public class App {

    public static void main(String[] args) {
        Mammoth mammoth = new Mammoth();
        mammoth.observe();
        mammoth.timePasses();
        mammoth.observe();
        mammoth.timePasses();
        mammoth.observe();
    }
}




/*The mammoth is calm and peaceful.
The mammoth gets angry!
The mammoth is furious!
The mammoth calms down.
The mammoth is calm and peaceful.
*/







0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:55466次
    • 积分:1626
    • 等级:
    • 排名:千里之外
    • 原创:55篇
    • 转载:42篇
    • 译文:42篇
    • 评论:8条