现在的位置: 首页 > 综合 > 正文

设计模式-结构型模式-享元

2017年12月08日 ⁄ 综合 ⁄ 共 2007字 ⁄ 字号 评论关闭

结构型模式:结构型对象模式不是对接口或实现进行组合的.而是描述了如何对一些对象进行组合,从而实现新功能的一些方法.
flyweight:运用共享技术有效的技持大量细粒度的对象.

package structure.flyweight;
/**
 *  A shared ConcreteFlyweight
 */
import java.io.*;

public class ConcreteFont implements Font {
    private String color;
    private int size;
    private String str;
   
    public ConcreteFont(String s) {
        str = s;
        //id = "The char is: " + s;
    }
    public void SetFont(String _color, int _size) {
        color = _color;
        size = _size;
    }
    public void GetFont() {
        System.out.println("String :" + str + "--- color is:" + color + "--- size is:" + size);
    }
}

 

package structure.flyweight;
/**
 *  A FlyWeight
 */
public interface Font  {
    public abstract void SetFont(String color, int size);
    public abstract void GetFont();
}

 

package structure.flyweight;
/**
 *  A Flyweight Factory
 */
import java.util.*;

public class FontFactory  {
    private Hashtable charHashTable = new Hashtable();
   
    public FontFactory() {
    }

    public Font GetFlyWeight(String s) {
        if(charHashTable.get(s) != null) {
            return (Font)charHashTable.get(s);
        } else {
            Font tmp = new ConcreteFont(s);
            charHashTable.put(s, tmp);
            return tmp;
        }
    }
    public Hashtable GetFactory() {
        return charHashTable;
    }
}

 

package structure.flyweight;
/**
 *  A test client
 */
import java.io.*;
import java.util.*;

public class Test  {
    public static void main(String[] args) {
        int[] size = {8, 9, 10, 11, 12};
        String[] color = {"FFFFFF", "000000", "FF00FF", "CCCCCC", "111111"};
        FontFactory myFontFactory = new FontFactory();
        String aString = "A test string";
        for(int i = 0; i < aString.length(); i++) {
            int j = 0;
            j = (int)Math.floor(Math.random()*5);
            //System.out.println("j is:" + j + "---" +aString.substring(i, i+1));
            myFontFactory.GetFlyWeight(aString.substring(i, i+1)).SetFont(color[j], size[j]);
        }
       
        Hashtable myHashTable = myFontFactory.GetFactory();
        System.out.println("Hash table size is:" + myHashTable.size());
        for(int i = 0; i < aString.length(); i++) {
            ((Font)myHashTable.get(aString.substring(i, i+1))).GetFont();
        }
    }
}

抱歉!评论已关闭.