• 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                               

  • 相关阅读:
    Spring Cloud云架构
    Spring Cloud云架构
    Spring Cloud云架构
    Spring Cloud云架构
    Spring Cloud Consul
    Spring Cloud Eureka
    构建Spring Cloud微服务分布式云架构
    数据库三范式
    redis3.0.0 集群安装详细步骤
    sql优化的几种方法
  • 原文地址:https://www.cnblogs.com/mxh-java/p/11070037.html
Copyright © 2020-2023  润新知