享元模式的目标是共享内存中的轻量级的对象,从而减少在内存中创建相同的对象,现在用一个牛排咖啡店来说明享元模式的原理:
现在有一个牛排咖啡店,里面有各种风味的牛排(Flavor),现在我们想用享元设计模式来实现这个牛排销售系统
先将代码奉上:
public interface Order
{
//将牛排卖给客人
public void sell();
//返回牛排的名字
public String getFlavor();
}
public class Flavor implements Order
{
private String name;
public Flavor(String name)
{
this.name=name;
}
@Override
public String getFlavor()
{
// TODO Auto-generated method stub
return name;
}
@Override
public void sell()
{
// TODO Auto-generated method stub
System.out.println("将"+name+"牛排卖给客人");
}
}
public class FlavorFactory
{
private Map map=new HashMap();
public Order getOrder(String key)
{
if(!map.containsKey(key))
map.put(key, new Flavor(key));
return (Order)map.get(key);
}
//获得内存中所有的对象
public int getTotal()
{
return map.size();
}
}
public class Client
{
private static FlavorFactory factory=new FlavorFactory();
public static void main(String[] args)
{
factory.getOrder("1");
factory.getOrder("2");
factory.getOrder("1");
factory.getOrder("2");
factory.getOrder("1");
factory.getOrder("2");
factory.getOrder("1");
factory.getOrder("2");
System.out.println("内存中所有Flavor:"+factory.getTotal());
}
}