zoukankan      html  css  js  c++  java
  • 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                               

  • 相关阅读:
    django 笔记4 数据库操作
    html关于不换行代码
    之前搭建的jenkins的一些笔记
    pip报错
    ssh 免密及加密远程脚本实现
    今天了解了些redis和memcached的知识
    django 笔记3
    来选择一款适合你网站的CMS建站程序吧
    如何预防和检测网页挂马?
    网页挂马方式
  • 原文地址:https://www.cnblogs.com/mxh-java/p/11070037.html
Copyright © 2011-2022 走看看