public interface IBike {
void billing(int time);
}
6.2 创建具体享元角色ConcreteFlyweight
创建共享单车类,其中单价是它的内部状态,不随环境而改变;总价是它的外部状态,随着环境改变而改变。
public class ShareBike implements IBike {//共享单车类
private int price = 1;//单价
private int total;//总价
@Override
public void billing(int time) {
total = price * time;
System.out.println("骑车花费了" + total + "元");
}
}
6.3 创建享元工厂FlyweightFactory
负责管理对象池和创建享元对象:
public class BikeFactory {
private static Map<String, IBike> pool = new HashMap<>();//使用HashMap来保存IBike对象
public IBike getBike(String name) {
IBike bike = null;
if (pool.containsKey(name)) {//如果存在对象的话,直接使用
System.out.println("押金已交,直接用车:" + name);
bike = pool.get(name);
} else {//对象不存在的话,先创建对象
bike = new ShareBike();
pool.put(name, bike);
System.out.println(name + "交100押金,可以用车了。");
}
return bike;
}
}