enum 實現售賣機,enum實現售賣機

來源:互聯網
上載者:User

enum 實現售賣機,enum實現售賣機
首先推薦一下Google的代碼風格

:https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.8.4.3-switch-default

enum售賣機1.定義售賣機接受的輸入命令:
package com.enumTest.enumStateMac;import java.util.Arrays;import java.util.Random;public enum Input {    NICKEL(5), DIME(10), QUARTER(25), DOLLAR(100), TOOTHPASTE(200), CHIPS(75), SODA(100), SOAP(50),    ABORT_TRANSACTION {        public int amout() {            throw new RuntimeException("ABORT.amout()");        }    },    STOP {        // last instance        public int amout() {            throw new RuntimeException("SHUT.amout()");        }    };    // 商品價格    int value;    Input(int value) {        this.value = value;    }    Input() {    }    int amount() {        return value;    }    static Random rand = new Random(47);    public static Input randomSelection() {        // Dont include STOP:        return values()[rand.nextInt(values().length - 1)];    }    public static void main(String[] args) {    }}
2.售賣機類
package com.enumTest.enumStateMac;import static net.mindview.util.Print.*;import java.util.EnumMap;import java.util.Iterator;import java.util.logging.Logger;import net.mindview.util.TextFile;import com.java.array.generator.Generator;enum Category {    // 定義 Category enum執行個體    MONEY(Input.NICKEL, Input.DIME, Input.QUARTER, Input.DOLLAR),    ITEM_SELECTION(Input.TOOTHPASTE, Input.CHIPS, Input.SODA, Input.SOAP),    QUIT_TRANSACTION(Input.ABORT_TRANSACTION),    SHUT_DOWN(Input.STOP);    // 初始化 Input 執行個體    private Input[] values;    Category(Input... types) {        values = types;    }    private static EnumMap<Input, Category> categories = new EnumMap<Input, Category>(Input.class);    // 填充categories <輸入內容 ,根據輸入得到的相應菜單>    static {        for (Category c : Category.class.getEnumConstants())            for (Input type : c.values)                categories.put(type, c);    }    // 根據輸入擷取 相應的類別菜單    public static Category categorize(Input input) {        return categories.get(input);    }}public class VendingMachine {    // 預設機器 state 為 休息狀態    private static State state = State.RESTING;    // 預設機器 amount =0 投幣金額    private static int amount = 0;    private static Input selection = null;    enum StateDuration {        TRANSIENT    } // Tagging enum    // 機器的狀態 枚舉執行個體如下:    // 待機狀態 投幣狀態 出貨狀態 找零狀態 中斷操作狀態    enum State {        // 按照輸入內容 進行不同反應        // 待機狀態 將執行:        RESTING {            void next(Input input) {                try {                    System.out.println("now State: " + state + " RESTING : input: " + input);                    Thread.sleep(10000l);                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                switch (Category.categorize(input)) {                // 如果輸入是金額 1.投幣金額設定 2.機器狀態設定為 投幣                case MONEY:                    amount += input.amount();                    state = ADDING_MONEY;                    break;// break to where                // 如果是 關機                case SHUT_DOWN:                    state = TERMINAL;                    // why ???                default:                }            }        },        // 如果機器是投幣狀態 將執行:        ADDING_MONEY {            void next(Input input) {                try {                    System.out.println("now State: " + state + " ADDING_MONEY : input: " + input);                    Thread.sleep(5000l);                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                switch (Category.categorize(input)) {                // 繼續投幣 操作                case MONEY:                    amount += input.amount();                    break;                // 選擇物品 操作                case ITEM_SELECTION:                    selection = input;                    // 金額不足                    if (amount < selection.amount())                        print("Insufficient money for " + selection);                    else                        // 出貨狀態                        state = DISPENSING;                    break;                // 取消操作                case QUIT_TRANSACTION:                    // 找零                    state = GIVING_CHANGE;                    break;                // 關閉                case SHUT_DOWN:                    state = TERMINAL;                default:                }            }        },        // 出貨        DISPENSING(StateDuration.TRANSIENT) {            void next() {                try {                    System.out.println("now State: " + state + " DISPENSING : input: ");                    Thread.sleep(5000l);                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                // 出貨,計費,置為找零狀態                print("here is your " + selection);                amount -= selection.amount();                state = GIVING_CHANGE;            }        },        GIVING_CHANGE(StateDuration.TRANSIENT) {            void next() {                try {                    System.out.println("now State: " + state + " GIVING_CHANGE : input: ");                    Thread.sleep(5000l);                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }                // 找零 置為待機                if (amount > 0) {                    print("Your change: " + amount);                    amount = 0;                }                state = RESTING;            }        },        TERMINAL {            void output() {                print("Halted");            }        };        private boolean isTransient = false;        State() {        }        State(StateDuration trans) {            isTransient = true;        }        // 操作狀態 :待機狀態 投幣狀態 此方法必須重寫        void next(Input input) {            throw new RuntimeException("Only call " + "next(Input input) for non-transient states");        }        // 在機器非自動運轉狀態:出貨狀態 找零狀態 此方法必須重寫        void next() {            throw new RuntimeException("Only call next() for " + "StateDuration.TRANSIENT states");        }        void output() {            print("over amount : " + amount);        }    }    // 售貨機 靜態方法    static void run(Generator<Input> gen) {        while (state != State.TERMINAL) {            Input inputTemp = gen.next();            if (null == inputTemp/* 限制性 返回Input 中的一個操作 */) {                return;            }            state.next(inputTemp/* 限制性 返回Input 中的一個操作 */);// 返回輸入的Input操作的                                                          // 相應            // 如果上一步操作是 待機狀態 投幣狀態 也就是說會有=下一步操作的 操作(會調用 next(para),transient            // 置為true)。            while (state.isTransient)                // state.isTransient 代表有下一步 操作                state.next();            state.output();        }    }    public static void main(String[] args) {        // 獲得一個 Input        Generator<Input> gen = new RandomInputGenerator();        if (args.length == 1)            // 輸入操作命令 完成命令 初始化            gen = new FileInputGenerator(args[0]);        run(gen);    }}// For a basic sanity check:class RandomInputGenerator implements Generator<Input> {    public Input next() {        return Input.randomSelection();    }}// Create Inputs from a file of ‘;’-separated strings:class FileInputGenerator implements Generator<Input> {    private Iterator<String> input;    public FileInputGenerator(String fileName) {        input = new TextFile(fileName, ";").iterator();    }    // 限制性 返回Input 中的一個操作    public Input next() {        if (!input.hasNext())            return null;        String inputNext = input.next().trim();        if (inputNext == null || "".equals(inputNext)) {            System.out.println("指令不合法");            return Input.ABORT_TRANSACTION;        }        Input inputGenerated = Enum.valueOf(Input.class, inputNext);        System.out.println(inputGenerated);        return inputGenerated;    }}
3.其他的協助類以及相關介面:
package com.java.array.generator;public interface Generator<T> {    T next();}
//: net/mindview/util/TextFile.javapackage net.mindview.util;import java.io.*;import java.util.*;public class TextFile extends ArrayList<String> {  // Read a file as a single string:  public static String read(String fileName) {    StringBuilder sb = new StringBuilder();    try {      BufferedReader in= new BufferedReader(new FileReader(        new File(fileName).getAbsoluteFile()));      try {        String s;        while((s = in.readLine()) != null) {          sb.append(s);          sb.append("\n");        }      } finally {        in.close();      }    } catch(IOException e) {      throw new RuntimeException(e);    }    return sb.toString();  }  // Read a file, split by any regular expression:  public TextFile(String fileName, String splitter) {    super(Arrays.asList(read(fileName).split(splitter)));    // Regular expression split() often leaves an empty    // String at the first position:    if(get(0).equals("")) remove(0);  }  // Normally read by lines:  public TextFile(String fileName) {    this(fileName, "\n");  }  } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.