- 享元模式的关键是使用一个称作享元的对象为其他对象提供共享的数据,而且能够保证使用享元的对象不能修改享元中的数据。
常见的三种角色
1.享元接口:定义了享元对外公开内部数据的方法和接受外部数据的方法
2.具体的享元:实现享元接口的类,这个类的实例称作享元对象或者享元。
3.享元工厂:负责创建和管理享元,可以通过一个散列表来管理享元。享元接口
public interface Flyweight {
public double getHeight();
public double getWidth();
public double getLength();
public void printMess(String mess);
}
享元工厂和享元类
public class FlyweightFactory {
private HashMap<String, Flyweight> hashMap;
static FlyweightFactory factory=new FlyweightFactory();
private FlyweightFactory(){
hashMap=new HashMap<String, Flyweight>();
}
public static FlyweightFactory getFactory(){
return factory;
}
public synchronized Flyweight getFlyweight(String key){
if(hashMap.containsKey(key)){
return hashMap.get(key);
}else{
double width=0,height=0,length=0;
String[] str=key.split("#");
width=Double.parseDouble(str[0]);
height=Double.parseDouble(str[1]);
length=Double.parseDouble(str[2]);
Flyweight ft=new ConcreteFlyweight(height, width, length);
hashMap.put(key, ft);
return ft;
}
}
class ConcreteFlyweight implements Flyweight{
private double height;
private double widht;
private double lenght;
public ConcreteFlyweight(double height, double widht, double lenght) {
super();
this.height = height;
this.widht = widht;
this.lenght = lenght;
}
public double getHeight() {
return height;
}
public double getWidth() {
return widht;
}
public double getLength() {
return this.lenght;
}
public void printMess(String mess) {
P.p(mess);
P.p("宽度:"+widht);
P.p("高度"+height);
P.p("长度"+lenght);
}
}
}
其他对象
public class Car {
Flyweight flyweight;
int power;
String name,color;
Car(Flyweight flyweight, int power, String name, String color) {
super();
this.flyweight = flyweight;
this.power = power;
this.name = name;
this.color = color;
}
public void print(){
P.p("color:"+color);
P.p("power:"+power);
P.p("name:"+name);
P.p("width_"+flyweight.getWidth());
P.p("height_"+flyweight.getHeight());
P.p("length_"+flyweight.getLength());
P.p();
}
}
测试
public class Application {
public static void main(String args[]){
FlyweightFactory factory=FlyweightFactory.getFactory();
double width=1.82,height=1.47,length=5.12;
String key=""+width+"#"+height+"#"+length;
Flyweight flyweight=factory.getFlyweight(key);
Car a6=new Car(flyweight, 128, "mazida", "red");
Car a7=new Car(flyweight,190, "bieke", "blue");
a6.print();
a7.print();
}
}
结果
color:red
power:128
name:mazida
width_1.82
height_1.47
length_5.12
color:blue
power:190
name:bieke
width_1.82
height_1.47
length_5.12