Programming to Interfaces(接口编程)
在我们的领域对象中,我经常使用接口来处理。因此在编译时我们没必要知道具体的实现类型。
讨论一下类:
public interface Shape {
public double getArea();
}
...
public class Rectangle implements Shape {
private double height;
private double width;
public Rectangle() {}
public Rectangle(double height, double width) {
this.height = height;
this.width = width;
}
@Override
public double getArea() {
return height * width;
}
}
...
public class Circle implements Shape {
...
}
...
public class ShapeContainer {
private List<Shape> shapes;
...
}
现在我们想把Shape保存到Mongo。Morphia面临的唯一的问题就是,当我们处理接口是那个实现类被创建。也就是说,当我们从Mongo中恢复第一个对象时,Morphia怎么知道
是映射到Rectangle还是Circle?
Morphia通过在Mongo的文档中保存一个叫“className”的属性,这个属性值对应的是java对象的一个类全名。
我们所要做的是确定所有的实现都加入到了Morphia实例中。
Morphia morphia = new Morphia();
morphia.map(Circle.class)
.map(Rectangle.class)
.map(ShapeShifter.class);
shape容器可以保存为一个嵌套的集合。
public class ShapeContainer {
@Embedded
private List<Shape> shapes;
...
}
或者一个应用集合
public class ShapeContainer {
@Reference
private List<Shape> shapes;
...
}
总而言之,Morphia是基于接口编程变的很简单
原文链接:http://code.google.com/p/morphia/wiki/UsingInterfaces