?
package 设计模式.享元模式; public abstract class Order { abstract void sell(); }
?
package 设计模式.享元模式; public class DishOrder extends Order { private String name ; public DishOrder(String name) { this.name = name; } @Override void sell() { System.out.println(" 外卖 "+ name+ " 一份 " ); } }
?
?
package 设计模式.享元模式; import java.util.concurrent.ConcurrentHashMap; public class DishFactory { private static ConcurrentHashMap<String,Order> map= new ConcurrentHashMap<String,Order>(); public static Order getInstance(String name){ Order order = map.get(name); if (order == null) { order = new DishOrder(name); order = map.putIfAbsent(name, order); } return map.get(name); } public static int getMapSize(){ return map.size(); } }
?
package 设计模式.享元模式; import java.util.ArrayList; import java.util.List; //在一个系统中如果有多个相同的对象,那么只共享一份就可以了,不必每个都去实例化一个对象 //数据库连接池,线程池等即是用享元模式的应用 //String类型就是使用了享元模式。String对象是final类型,对象一旦创建就不可改变。在JAVA中字符串常量都是存在常量池中的 public class FlyweightTest { private static List <Order> list = new ArrayList<Order>(); public static void main(String[] args) { FlyweightTest client = new FlyweightTest(); client.setOrder("西红柿炒鸡蛋"); client.setOrder("肉末茄子"); client.setOrder("宫保鸡丁"); client.setOrder("宫保鸡丁"); client.setOrder("宫保鸡丁"); client.setOrder("红烧肉"); client.setOrder("西红柿炒鸡蛋"); for (int i = 0; i < list.size(); i++) { list.get(i).sell(); } System.out.println("点餐 了 : " + list.size()+" 份"); System.out.println("对象 数 : " +DishFactory.getMapSize()+" --"); } public void setOrder(String name){ list.add(DishFactory.getInstance(name)); } }
?
?
?
?
?
?
?
?
?
原文:http://knight-black-bob.iteye.com/blog/2218915