设计模式之享元flyWieght模式、精简不浪费

二十、flyWeight享元 有相同的部分就共享 采取精简政策

public class BigChar {
    private char charName;
    private String fontData;
    public BigChar(char charName){
        this.charName=charName;
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader("big" + charName + ".text"));
            String line;
            StringBuffer nuf = new StringBuffer();
            while((line=bufferedReader.readLine())!=null){
                nuf.append(line);
                nuf.append("\n");
            }
            bufferedReader.close();
            this.fontData=nuf.toString();
        } catch (Exception e) {
            this.fontData=charName+"?";
        }
    }
    public void print(){
        System.out.println(fontData);
    }
}
public class BigCharFactory {
    private Hashtable pool=new Hashtable();
    private static BigCharFactory singleton=new BigCharFactory();
    private BigCharFactory(){

    }
    public static BigCharFactory getInstance(){
        return singleton;
    }
    public synchronized BigChar getBigChar(char name){
        BigChar bigChar=(BigChar) pool.get(name);
        if (bigChar==null){
            bigChar=new BigChar(name);
            pool.put(name,bigChar);
        }
        return bigChar;
    }
}
public class BigString {
    private BigChar[] bigChars;
    public BigString(String string){
        bigChars = new BigChar[string.length()];
        BigCharFactory factory=BigCharFactory.getInstance();
        for (int i = 0; i < bigChars.length; i++) {
            bigChars[i]=factory.getBigChar(string.charAt(i));
        }
    }
    public void print(){
        for (int i = 0; i < bigChars.length; i++) {
            bigChars[i].print();
        }
    }
}
public class Test {
    public static void main(String[] args) {
        BigString bigString = new BigString("213242112");
        bigString.print();
    }
}

你可能感兴趣的:(设计模式)