001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License.
018 *
019 */
020package org.apache.mina.example.tennis;
021
022/**
023 * A tennis ball which has TTL value and state whose value is one of 'PING' and
024 * 'PONG'.
025 *
026 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
027 */
028public class TennisBall {
029    private final boolean ping;
030
031    private final int ttl;
032
033    /**
034     * Creates a new ball with the specified TTL (Time To Live) value.
035     * 
036     * @param ttl The time to live
037     */
038    public TennisBall(int ttl) {
039        this(ttl, true);
040    }
041
042    /**
043     * Creates a new ball with the specified TTL value and PING/PONG state.
044     */
045    private TennisBall(int ttl, boolean ping) {
046        this.ttl = ttl;
047        this.ping = ping;
048    }
049
050    /**
051     * @return the TTL value of this ball.
052     */
053    public int getTTL() {
054        return ttl;
055    }
056
057    /**
058     * @return the ball after {@link TennisPlayer}'s stroke.
059     * The returned ball has decreased TTL value and switched PING/PONG state.
060     */
061    public TennisBall stroke() {
062        return new TennisBall(ttl - 1, !ping);
063    }
064
065    /**
066     * @return string representation of this message (<code>[PING|PONG]
067     * (TTL)</code>).
068     */
069    @Override
070    public String toString() {
071        if (ping) {
072            return "PING (" + ttl + ")";
073        } else {
074            return "PONG (" + ttl + ")";
075        }
076    }
077}