参考《设计模式的艺术软件开发人员内功修炼之道》-刘伟 著
模式介绍
享元模式通过共享对象池对象,达到减少对象生成的目的
实验代码
package FlyweightPattern;
import java.util.HashMap;
class Position {
private int x, y;
public Position(int _x, int _y) {
x = _x;
y = _y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int _x) {
x = _x;
}
public void setY(int _y) {
y = _y;
}
}
interface Flyweight {
public void displayColor();
public void displayPosition(Position pos);
}
class WhiteFlyweight implements Flyweight {
@Override
public void displayColor() {
// TODO Auto-generated method stub
System.out.println("WhiteFlyweight is displayColor");
}
@Override
public void displayPosition(Position pos) {
// TODO Auto-generated method stub
System.out.println("WhiteFlyweight is displayPosition : x is " + pos.getX() + " , y is " + pos.getY());
}
}
class BlackFlyweight implements Flyweight {
@Override
public void displayColor() {
// TODO Auto-generated method stub
System.out.println("BlackFlyweight is displayColor");
}
@Override
public void displayPosition(Position pos) {
// TODO Auto-generated method stub
System.out.println("WhiteFlyweight is displayPosition : x is " + pos.getX() + " , y is " + pos.getY());
}
}
class FlyweightFactory {
private final static FlyweightFactory inst = new FlyweightFactory();
private HashMap flyweightMap = new HashMap<String, Flyweight>(100);
private FlyweightFactory() {
Flyweight wfw1 = new WhiteFlyweight();
Flyweight wfw2 = new WhiteFlyweight();
Flyweight bfw1 = new BlackFlyweight();
Flyweight bfw2 = new BlackFlyweight();
flyweightMap.put("wfw1", wfw1);
flyweightMap.put("wfw2", wfw2);
flyweightMap.put("bfw1", bfw1);
flyweightMap.put("bfw2", bfw2);
}
public static FlyweightFactory getFlyweightFactory() {
return inst;
}
public Flyweight getFlyweight(String key) {
Flyweight fw = (Flyweight) flyweightMap.get(key);
return fw;
}
}
public class FlyweightPatternTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
FlyweightFactory factory = FlyweightFactory.getFlyweightFactory();
Flyweight wfw1 = factory.getFlyweight("wfw1");
Flyweight wfw2 = factory.getFlyweight("wfw2");
Flyweight bfw1 = factory.getFlyweight("bfw1");
Flyweight bfw2 = factory.getFlyweight("bfw2");
wfw1.displayColor();
wfw1.displayPosition(new Position(1, 1));
wfw2.displayColor();
wfw2.displayPosition(new Position(1, 2));
bfw1.displayColor();
bfw1.displayPosition(new Position(2, 1));
bfw2.displayColor();
bfw2.displayPosition(new Position(2, 2));
}
}
实验结果
WhiteFlyweight is displayColor
WhiteFlyweight is displayPosition : x is 1 , y is 1
WhiteFlyweight is displayColor
WhiteFlyweight is displayPosition : x is 1 , y is 2
BlackFlyweight is displayColor
WhiteFlyweight is displayPosition : x is 2 , y is 1
BlackFlyweight is displayColor
WhiteFlyweight is displayPosition : x is 2 , y is 2
结论
- 抽象享元,享元工厂,具体享元,构成了享元模式
- 具体享元可以内置状态(如white,black),外置状态(pos)通过关联方式通过入参传入