Created
July 4, 2017 13:07
-
-
Save cattaka/c17bb51491359cfb914a897fb6f5e5d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package pattern1; | |
import java.util.HashMap; | |
import java.util.HashSet; | |
import java.util.Set; | |
import java.util.UUID; | |
/** | |
* Created by cattaka on 17/07/04. | |
* <p> | |
* Gist for https://twitter.com/Kory__3/status/882212409967919104 | |
*/ | |
public abstract class VotesMap<K, V> extends HashMap<K, V> { | |
public static class VoteCacheByScores extends VotesMap<VoteScore, Set<VotePoint>> { | |
public VoteCacheByScores() { | |
super(VoteScore.class); | |
} | |
@Override | |
Set<VotePoint> createNewSet() { | |
return new HashSet<>(); | |
} | |
} | |
public static class UuidToPlayerVotesMap extends VotesMap<UUID, VoteCacheByScores> { | |
public UuidToPlayerVotesMap() { | |
super(UUID.class); | |
} | |
@Override | |
VoteCacheByScores createNewSet() { | |
return new VoteCacheByScores(); | |
} | |
} | |
public static class VotePointVotesCache extends VotesMap<VotePoint, Set<Vote>> { | |
public VotePointVotesCache() { | |
super(VotePoint.class); | |
} | |
@Override | |
Set<Vote> createNewSet() { | |
return new HashSet<>(); | |
} | |
} | |
private Class<K> mKeyClass; | |
private VotesMap(Class<K> keyClass) { | |
mKeyClass = keyClass; | |
} | |
@Override | |
public V get(Object o) { | |
if (mKeyClass.isInstance(o)) { | |
//noinspection unchecked | |
K key = (K) o; // NOTE: 上でisInstanceを通してるので大丈夫 | |
// NOTE: contains(o)がtrueでも、別系統でput(o,null)されてるとnullが返るので、実際に値を取得してチェック。 | |
V result = super.get(o); | |
if (result == null) { | |
result = createNewSet(); | |
put(key, result); | |
} | |
return result; | |
} else { | |
// 一部の異なるクラス間でequalsを使うとClassCastExceptionが飛ぶものがあるので、正直危ない | |
return super.get(o); | |
} | |
} | |
abstract V createNewSet(); | |
} | |
class VoteScore { | |
} | |
class VotePoint { | |
} | |
class Vote { | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment