前言
"若存在则取回,若不存在则创建后取回"
这种逻辑在日常的编程中极为常见。例如带有缓存功能的对象创建工厂。
平常实现方法
首先假设我们有一个工厂类,可以创建对象,并缓存对象,对象缓存下来下次就不需要再创建一次,减少开销。工厂类大致如下:
java
/** * * * @author beanlam * @date 2015年7月1日 上午10:46:47 * @version 1.0 * */ public class Factory { private static ConcurrentMap<String, Person> men = new ConcurrentHashMap<String, Person>(); private static ConcurrentMap<String, Person> women = new ConcurrentHashMap<String, Person>(); public static Man getManByName(String name) { if (men.get(name) == null) { Man newMan = new Man(name); men.putIfAbsent(name, newMan); } return (Man)men.get(name); } public static Woman getWomanByName(String name) { if (women.get(name) == null) { Woman newWoman = new Woman(name); women.putIfAbsent(name, newWoman); } return (Woman)women.get(name); } } class Person { String name; Person (String name) { this.name = name; } } class Man extends Person { Man(String name) { super(name); } } class Woman extends Person { Woman(String name) { super(name); } }
另外一种实现
java
/** * * * @author beanlam * @date 2015年7月1日 上午10:46:47 * @version 1.0 * */ public class Factory { private static ConcurrentMap<String, Person> men = new ConcurrentHashMap<String, Person>(); private static ConcurrentMap<String, Person> women = new ConcurrentHashMap<String, Person>(); public static Man getManByName(final String name) { return (Man)get(men, name, new Creatable<Person>() { @Override public Person create() { // TODO Auto-generated method stub return new Man(name); } }); } public static Woman getWomanByName(final String name) { return (Woman)get(women, name, new Creatable<Person>() { @Override public Person create() { // TODO Auto-generated method stub return new Woman(name); } }); } private static Person get(ConcurrentMap<String, Person> which, String name, Creatable<Person> creatable) { Person person = which.get(name); if (person == null) { person = creatable.create(); Person prePerson = which.putIfAbsent(name, person); if (prePerson != null) { person = prePerson; } } return person; } private interface Creatable<V> { V create(); } } class Person { String name; Person (String name) { this.name = name; } } class Man extends Person { Man(String name) { super(name); } } class Woman extends Person { Woman(String name) { super(name); } }