运用共享技术有效地支持大量细粒度的对象
享元模式共享的关键是区分内蕴状态(Internal state)和外蕴状态(external state)。
内蕴状态是存储在享元对象内部不会改变的,可以共享。
外蕴状态是随环境改变的,不可以共享的状态。它可以改变方法的行为。
abstract public class Flyweight
{
//state外蕴状态,改变方法的行为
abstract public void operation(String state);
}
public class ConcreteFlyweight extends Flyweight
{
private Character instrinsicState=null;
public ConcreteFlyweight(Character state)
{
this.instrinsicState=state;
}
public void operation(String state)
{
System.out.print("\nInstrinsic State="+instrinsicState+",Extrinsic State = "+state);
}
}
public class FlyweightFactory
{
private HashMap flies=new HashMap();
//根据内蕴状态构造对象
public Flyweight factory(Character state)
{
if(flies.containKey(state))
{
return (Flyweight)flies.get(state)
}
else
{
Flyweight fly=new ConcreteFlyweight(state);
flies.put(state,fly);
return fly;
}
}
public state void main(String[] args)
{
FlyweightFactory factory=new FlyweightFactory();
Flyweight fly=factory.factory(new Character('a'));
fly.operation("First call");
Flyweight fly2=factory.factory(new Character('b'));
fly2.operation("Second call");
Flyweight fly3=factory.factory(new Character('a'));
fly3.operation("Third call");
}
}