我们知道,奥迪A6汽车有很多种不同的地方,比如讲可能颜色,动力等的不一样,但是往往同为奥迪A6的汽车,他们的高度、宽度、长度都是一样的。现在如果我们系统中会涉及到这些汽车,如果我们没一个对象(奥迪A6)的成员变量里面都有高度、宽度、长度,那么在内存中就存在了大量的重复的数据,必然浪费了内存空间,现在如果我们可以把这些相同的数据放到一个对象里面,比如叫做CarData,而在每辆汽车里面有个CarData,这样就可以避免掉了浪费内存空间,并且还可以很容易的更改里面的数据,这就是享元模式,其中的CarData的实例就是一个享元。
享元模式例子:
Java代码
复制代码
- /**
- * 享元
- * @author--http://www.lookhan.com
- *
- */
- public class CarData {
- private int height;
- private int width;
- private int length;
- public int getHeight() {
- return height;
- }
- public void setHeight(int height) {
- this.height = height;
- }
- public int getWidth() {
- return width;
- }
- public void setWidth(int width) {
- this.width = width;
- }
- public int getLength() {
- return length;
- }
- public void setLength(int length) {
- this.length = length;
- }
- }
- public class AoDiOne {
- CarData carData;
- String color;
- double power;
- }
- public class AoDiTwo {
- CarData carData;
- String color;
- double power;
- }