共享模式_共享对象,避免内存浪费(避免重复创建相同的对象)

/**
* 需要被共享的对象
* @author maikec
* @date 2019/5/17
*/
public class Flyweight {
private String name;
public Flyweight(String name){
this.name = name;
}
public String getName() {
return name;
}
}
/**
* @author maikec
* @date 2019/5/17
*/
public class FlyweightFactory {
private static FlyweightFactory ourInstance = new FlyweightFactory();
@Getter
private final Map<String, Flyweight> pool = Collections.synchronizedMap( new HashMap<>( ) );
public static FlyweightFactory getInstance() {
return ourInstance;
}
private FlyweightFactory() {
}
public Flyweight getFlyweight(String flyweightName){
if (pool.containsKey( flyweightName )){
return pool.get( flyweightName );
}else{
Flyweight flyweight = new Flyweight( flyweightName );
pool.putIfAbsent( flyweightName,flyweight );
return flyweight;
}
}
}
/**
* @author maikec
* @date 2019/5/17
*/
public class FlyweightDemo {
public static void main(String[] args) {
FlyweightFactory instance = FlyweightFactory.getInstance();
System.out.println( instance.getFlyweight( "Flyweight" ).getName() );
System.out.println( instance.getFlyweight( "Flyweight" ).getName() );
System.out.println( instance.getFlyweight( "Flyweight1" ).getName() );
// 需要配置虚拟机 -ea 参数启用assert功能
assert 2==instance.getPool().size();
}
}
附录
github.com/maikec/patt… 个人GitHub设计模式案例
声明
引用该文档请注明出处