共享类的接口:
public abstract class FlyWeight {
protected int x;
protected int y;
public abstract void display(int x,int y);
}
具体的FlyWeight:
public class BlackFlyWeight extends FlyWeight {
@Override
public void display(int x, int y) {
System.out.println("●:("+x+","+y+")");
}
}
public class WhiteFlyWeight extends FlyWeight {
@Override
public void display(int x, int y) {
System.out.println("○:("+x+","+y+")");
}
}
享元工厂:
public class FlyWeightFactory {
private static Hashtable<Integer,FlyWeight> hashtable=new Hashtable<Integer,FlyWeight>();
public static FlyWeight getFlyWeight(int key) {
if (hashtable.containsKey(key)) {
return hashtable.get(key);
} else if(key%2==0){
WhiteFlyWeight whiteFlyWeight = new WhiteFlyWeight();
hashtable.put(key, whiteFlyWeight);
return whiteFlyWeight;
}else {
BlackFlyWeight blackFlyWeight=new BlackFlyWeight();
hashtable.put(key, blackFlyWeight);
return blackFlyWeight;
}
}
}
测试类:
public class Client {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
FlyWeight flyWeight = FlyWeightFactory.getFlyWeight(i);
flyWeight.display(i, new Random().nextInt(20));
}
}
}