我正试图在一个生成云的程序中应用飞重模式。我有一个表示云的内在状态的类。云类型由其属性定义。
class CloudType {
float size;
float altitude;
String color;
String texture;
public void display(x, y) {}
}
class ConcreteCloud {
float x;
float y;
CloudType cloudType;
void display() {
cloudeType.display(x, y);
}
}
我想创建一个CloudType工厂,它将这些特性作为参数,如果CloudType存在,则返回相应的CloudType实例,否则事先创建并存储它。
class CloudTypeFactory {
// SomeContainer<CloudType> container;
public CloudType getCloudType(float size, float altitude, String color, String texture) {
CloudType instance = // container get corresponding cloudType
if (instance == null) {
instance = new CloudeType(size, altitude, color, texture);
container.add(instance);
}
return instance;
}
}
问题是:我对应该使用哪个容器有疑问。
我对使用哪种容器有疑问,因此对架构本身也有疑问。可以使用HashSet,但搜索的复杂度与CloudType中的属性数量成正比,这似乎并不正确。在我在网上读到的例子中,作者使用了一个HashMap,其关键是CloudType的名称:这就违背了IMO的目的,因为在这种情况下,可能会有无限多的云类型。
equals()
和 hashCode()
对于 CloudType
类,这样你就可以在Map中存储实例。size
, altitude
, color
和 texture
到它。CloudType
.类似这样的情况。
class CloudType {
float size;
float altitude;
String color;
String texture;
private static final Map<Integer, CloudType> CACHE = new HashMap<>();
private CloudType(float size, float altitude, String color, String texture) {
this.size = size;
this.altitude = altitude;
this.color = color;
this.texture = texture;
}
public static CloudType lookup(float size, float altitude, String color, String texture) {
int hashKey = hashCode(size, altitude, color, texture);
return CACHE.computeIfAbsent(hashKey, k -> new CloudType(size, altitude, color, texture));
}
public void display(float x, float y) {}
//TODO generate equals() method
@Override
public int hashCode() {
return hashCode(size, altitude, color, texture);
}
private static int hashCode(float size, float altitude, String color, String texture) {
return Objects.hash(size, altitude, color, texture);
}
}
你在为蝇量级设计一个合适的关联存储时面临的问题可能是一个症状,即你的情况可能不是蝇量级模式的好目标。特别是,对象的内在状态中有两块是浮点值。这是不寻常的。在实践中,这意味着你可以拥有无穷多的对象,而它们的高度或大小却相差无几。
您所设计的解决方案应该取决于对这种数据建模的实际需求,以及在多大程度上可以实现 CloudTypes
被客户端代码重用。如果它们是 不 因为浮点精度很重要,所以不适合使用Flyweight。相反,如果在实践中,只有有限的几个 size
和 altitude
值,那么将这些值进行分离,并使用它们来构造一个主键,以便在关联存储中使用。