首页 > 代码库 > 设计模式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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。