码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式12-享元模式

时间:2014-06-23 00:04:26      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   java   

1. 概念

      享元模式(FlyWeight),运用共享技术有效的支持大量细粒度的对象 

2. 案例 

 

/**********************************************************************
 * <pre>
 * FILE : Demo01.java
 * CLASS : Demo01
 *
 * AUTHOR : Liaokailin
 *
 * FUNCTION : TODO
 *
 *
 *======================================================================
 * CHANGE HISTORY LOG
 *----------------------------------------------------------------------
 * MOD. NO.|   DATE   |   NAME  | REASON  | CHANGE REQ.
 *----------------------------------------------------------------------
 *             |2014-3-7|Liaokailin| Created |
 * DESCRIPTION:
 * </pre>
 ***********************************************************************/
package org.demo.fylweight.demo01;

import java.util.HashMap;
import java.util.Map;


interface Flyweight{
    void action(int arg) ;
}


class FlyweightImpl implements Flyweight{
    @Override
    public void action(int arg) {
        System.out.println("the value of param : " + arg);
    }
}

@SuppressWarnings("unchecked")
class FlyweightFactory{
    @SuppressWarnings("rawtypes")
    private static Map flyweights = new HashMap() ;
    public FlyweightFactory(String arg){
        flyweights.put(arg, new FlyweightImpl()) ;
    }
    
    public static Flyweight getFlyweight(String key){
        if(flyweights.get(key)==null){
            flyweights.put(key, new FlyweightImpl()) ;
        }
        return (Flyweight) flyweights.get(key) ;
    }
    
    public static int getSize(){
        return flyweights.size() ;
    }
}


public class Demo01 {
       public static void main(String args[]){
           Flyweight fly1 = FlyweightFactory.getFlyweight("a");
           System.out.println(fly1);
           fly1.action(1) ;
           Flyweight fly2 = FlyweightFactory.getFlyweight("a");
           System.out.println(fly1 == fly2);
           
           Flyweight fly3 = FlyweightFactory.getFlyweight("b"); 
           fly3.action(2); 
           Flyweight fly4 = FlyweightFactory.getFlyweight("c"); 
           fly4.action(3); 
           Flyweight fly5 = FlyweightFactory.getFlyweight("d");
           fly5.action(4); 
           System.out.println(FlyweightFactory.getSize());
           
           
       }
}

 

结果:

 

org.demo.fylweight.demo01.FlyweightImpl@530cf2
the value of param : 1
true
the value of param : 2
the value of param : 3
the value of param : 4
4

 

 

设计模式12-享元模式,布布扣,bubuko.com

设计模式12-享元模式

标签:des   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/liaokailin/p/3799995.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!