Java设计模式--享元模式
Posted mxh-java
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java设计模式--享元模式相关的知识,希望对你有一定的参考价值。
import java.util.HashMap; /** * 享元模式 * @author 尘世间迷茫的小书童 * */ public class Flyweight public static void main(String[] args) for(int i=0; i<5; i++) Cluster library = ClusterFactory.getCluster("阅读"); library.setClusterName("中国国家图书馆"); library.setClusterType("一级"); library.use(); System.out.println(library); Cluster gymnasium = ClusterFactory.getCluster("运动"); gymnasium.setClusterName("中国国家体育馆"); gymnasium.setClusterType("一级"); gymnasium.use(); System.out.println(gymnasium); int count = ClusterFactory.getClusterSize(); System.out.println("对象池: " + count); class Library extends Cluster @Override public void use() // TODO Auto-generated method stub System.out.println("图书馆名称: " + this.clusterName + " 建筑类别: " + this.clusterType + " 用处: " + this.effect); public Library(String effect) super(); this.effect = effect; class Gymnasium extends Cluster @Override public void use() // TODO Auto-generated method stub System.out.println("体育馆名称: " + this.clusterName + " 建筑类别: " + this.clusterType + " 用处: " + this.effect); public Gymnasium(String effect) super(); this.effect = effect; class ClusterFactory /** * 对象池 */ private static final HashMap<String, Cluster> map = new HashMap<String, Cluster>(); private ClusterFactory() public static Cluster getCluster(String effect) Cluster cluster = map.get(effect); if(null == cluster) if("阅读".equals(effect)) cluster = new Library("阅读"); map.put("阅读", cluster); if("运动".equals(effect)) cluster = new Gymnasium("运动"); map.put("运动", cluster); return cluster; public static int getClusterSize() return map.size();
推荐阅读: https://www.cnblogs.com/V1haoge/p/6542449.html
以上是关于Java设计模式--享元模式的主要内容,如果未能解决你的问题,请参考以下文章