FlyWeight模式

一、Flyweight模式的意图:

缓存(共享)可以共同的对象、属性,避免创建大量的重复对象、内容。

二、Flyweight模式的特点:

为重复或可共享的对象、属性设置一个缓冲,称为内部属性。这些内部属性一般情况下都是不可修改的,也就是在第一个对象、属性被创建后,就不会去修改了(否则就没意义了)。

除了共享对象、属性之外,还有一些是基于应用环境,或是实时数据,这些无法共享的东西我们称为外部状态。

在Flyweight模式应用中,通常修改的是外部状态属性,而内部状态属性一般都是用于参考或计算时引用。

三、Flyweight模式的构成:


Flyweight模式一般由几个部分组成:

·Flyweight接口(抽象类) :定义了一个可共享的元类
·Flyweight实现类:实现了元类中的操作,而且可能会提供一个用于保存内部状态(共享属性)的空间
·Flyweight Factory:创建Flyweight的工厂类,创建后将其保存到Flyweight Pool中
·Flyweight Pool:缓冲Flyweight对象的池,通常包含在工厂类中


四、Flyweight模式的简单实现

1.Flyweight:

package  com.pattern.flyweight2;

public   abstract   class  Flyweight
{
    
public abstract void operation();
}


2.ConcreateFlyweight:
package  com.pattern.flyweight2;

public   class  ConcreateFlyweight  extends  Flyweight
{
    
private Object key;

    
public ConcreateFlyweight(Object key)
    
{
        
this.key = key;
    }


    @Override
    
public void operation()
    
{
        System.out.println(
"key:" + key);
    }


}

3.FlyweightFactory:

package  com.pattern.flyweight2;

import  java.util.Hashtable;

@SuppressWarnings(
" unchecked " )
public   class  FlyweightFactory
{
 //Flyweight pool
    
private Hashtable flyweights = new Hashtable();

    
public Flyweight getFlyweight(Object key)
    
{
        Flyweight flyweight 
= null;
        
if(flyweights.containsKey(key))
        
{
            flyweight 
= (Flyweight) flyweights.get(key);
        }

        
if (!flyweights.containsKey(key))
        
{
            flyweight 
= new ConcreateFlyweight(key);
            flyweights.put(key, flyweight);
        }

        
return flyweight;
    }

    
    
public int getFlyweightsSize()
    
{
        
return flyweights.size();
    }

}


4.测试类:

package  com.pattern.flyweight2;

public   class  Client
{
    
private Flyweight f1 = null;
    
private Flyweight f2 = null;
    
private Flyweight f3 = null;
    
private Flyweight f4 = null;
    FlyweightFactory factory 
= new FlyweightFactory();

    
public Client()
    
{
        f1 
= factory.getFlyweight("baidu");
        f2 
= factory.getFlyweight("google");
        f3 
= factory.getFlyweight("baidu");
        f4 
= factory.getFlyweight("google");
    }


    
public void show()
    
{
        f1.operation();
        f2.operation();
        f3.operation();
        f4.operation();
        System.out.println(factory.getFlyweightsSize());
    }


    
public static void main(String[] args)
    
{
        Client client 
= new Client();
        client.show();
    }

}

也就是在缓冲这一点上,体现了Flyweight模式的精髓。

 

转自:http://supercrsky.iteye.com/blog/372714

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