首页 > 代码库 > 设计模式12-享元模式

设计模式12-享元模式

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@530cf2the value of param : 1truethe value of param : 2the value of param : 3the value of param : 44